﻿#include "StdAfx.h"
#include "DlgMesSet.h"
#include "Mes.h"
#include "ProcessInfoCollect.h"
#include "MesGSoap.h"


extern "C" __declspec(dllexport) DHInterface* Export(void)
{
	return (DHInterface*)new CMes();
}
CMesSendInfo *g_pCMesSendInfo = NULL;

HANDLE *g_pHThead = NULL;



BOOL RenameFile(CString const& strLocalFilePath, CString const & strSymbol)
{
	CString	strFullFilePath;	//带路径文件全名

	CString strFilePath;		//文件夹路径

	CString strFileExtendName;	//文件扩展名

	CString strFileName;		//文件名，带扩展名

	CString strFile;			//文件名，不带扩展名

	CString strNewFilePath;		//新文件 带路径全名

	CString strNewFile;			//新文件名

	strFullFilePath = strLocalFilePath;

	strFilePath = strFullFilePath.Left(strFullFilePath.ReverseFind('\\')+1);

	strFileName = strFullFilePath.Right(strFullFilePath.GetLength()-strFullFilePath.ReverseFind('\\')-1);

	strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.ReverseFind('.')-1);

	strFile = strFileName.Left(strFileName.Find('.'));

	strNewFile.Format(_T("%s%s"),strFile,strSymbol);

	strNewFilePath.Format(_T("%s%s.%s"),strFilePath,strNewFile,strFileExtendName);

	try
	{
		CFile::Rename(strFullFilePath,strNewFilePath);	
	}
	catch (...)
	{
		return FALSE;
	}
	return TRUE;
}


BOOL ReversalRenameFile(CString const & strLocalFilePath, CString const & strSymbol)
{
	CString	strFullFilePath;	//带路径文件全名

	CString strFilePath;		//文件夹路径

	CString strFileExtendName;	//文件扩展名

	CString strFileName;		//文件名，带扩展名

	CString strFile;			//文件名，不带扩展名

	CString strNewFilePath;		//新文件 带路径全名

	CString strNewFile;			//新文件名

	int iLenght = strSymbol.GetLength();

	strFullFilePath = strLocalFilePath;

	strFilePath = strFullFilePath.Left(strFullFilePath.ReverseFind('\\')+1);

	strFileName = strFullFilePath.Right(strFullFilePath.GetLength()-strFullFilePath.ReverseFind('\\')-1);

	strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.ReverseFind('.')-1);

	strFile = strFileName.Left(strFileName.Find('.'));

	strNewFile = strFile.Left(strFile.Find(strSymbol));

	strNewFilePath.Format(_T("%s%s.%s"),strFilePath,strNewFile,strFileExtendName);

	try
	{
		CFile::Rename(strFullFilePath,strNewFilePath);	
	}
	catch (...)
	{
		return FALSE;
	}
	return TRUE;
}

void GetFilePath(std::vector<CString>& vFilePathList,CString & strDir)
{
	CFileFind finder;

	if (strDir == _T(""))
	{
		return;
	}
	else 
	{
		if (strDir.Right(1) != _T(""))
		{
			strDir += _T("\\");
		}
		strDir += _T("*.*");
	}

	BOOL isNotEmpty = finder.FindFile(strDir);//总文件夹，开始遍历 
	while(isNotEmpty)
	{
		isNotEmpty = finder.FindNextFile();//查找文件 
		CString filename = finder.GetFilePath();//获取文件的路径，可能是文件夹，可能是文件 
		if (!(finder.IsDirectory()))
		{	
			//如果是文件则加入文件列表
			vFilePathList.push_back(filename);//将一个文件路径加入容器
		} 
		else
		{													//递归遍历用户文件夹，跳过非用户文件夹
			if (!(finder.IsDots()||finder.IsHidden()||finder.IsSystem()||finder.IsTemporary()||finder.IsReadOnly()))
			{
				GetFilePath(vFilePathList,filename+_T("\\"));
			}
		}
	}
}



CMes* g_This = NULL;

CMes::CMes()
	:m_strLineCode(_T(""))
	, m_strIP(_T(""))
	, m_strSectionCode(_T(""))
	, m_strEquipmentCode(_T(""))
	, m_strEquipmentName(_T(""))
	, m_strLocalFilePath(_T(""))
	, m_strServerFilePath(_T(""))
	, m_strFactory(_T(""))
	, m_strEQM(_T(""))
	, m_isSendHttpMSG(FALSE)
	, m_bSendOK(FALSE)
	, m_bSendNG(FALSE)
	, m_bSendNGCrop(FALSE)
	, m_bSendCover(FALSE)
	, m_bRename(FALSE)
	, m_strLocalRootPath(_T(""))
	, m_strRootPathSymbol(_T(""))
	, m_strRenameSymbol(_T(""))
	, m_ThreadFtpUpload(NULL)
	, m_intervalMinute(0)
	, m_iThreadNumber(1)
	, m_strCrrentBatch(_T(""))
	, m_strRecipeCode(_T(""))
	, m_strRecipeVison(_T(""))
	, m_strProductCode(_T(""))
	, m_cstrRecipePath(_T(""))
	, m_iConnectStauts(0)
	, m_bExit(FALSE)
	, m_useMes(1)
	, m_nLogType(0)
	, m_cstrResourceCode(_T(""))
	, m_cstrUserName(_T(""))
	, m_cstrUserPassword(_T(""))
	, m_cstrOperatorPassword(_T(""))
	, m_cstrOperatorID(_T(""))	
	,m_nHeartBeatTime(10)
	,m_nLogSaveDays(30)
	,m_cstrSoapAddr("10.36.23.54")
	,m_nSoapPort(50899)
	, PlantArea(0)
{
	m_pSoapMesLog = CSoapMesLog::getInstance();

	m_hvQueue = NULL;
	
	m_nPort = 0;
	
	m_hv_SocketHandle = NULL;
	
	m_bConnected = FALSE;
	
	m_nType = 0;	

	m_cJsonRecipes.Clear();

	m_cJsonResend.Clear();

	m_pCJsonRecipeParam = NULL;
	
//	m_record.m_strFilePath.Format(_T("./Log/UploadFileRecord.txt"));
	
	InitializeCriticalSection(&m_csUploadTUple);

	InitializeCriticalSection(&m_csCurrentDisk);

	InitializeCriticalSection(&m_csWriteTuple);

	InitializeCriticalSection(&m_csBConnect);

	InitializeCriticalSection(&m_csSoapProcessParam);

	GetLocalTime(&m_currentTime);

	curl_global_init(CURL_GLOBAL_ALL);

}

CMes::~CMes()
{
	if (m_pCJsonRecipeParam)
	{
		delete [] m_pCJsonRecipeParam;

		m_pCJsonRecipeParam = NULL;
	}
	curl_global_cleanup();

	DeleteCriticalSection(&m_csUploadTUple);

	DeleteCriticalSection(&m_csCurrentDisk);

	DeleteCriticalSection(&m_csWriteTuple);

	DeleteCriticalSection(&m_csBConnect);

	DeleteCriticalSection(&m_csSoapProcessParam);
}

//int CMes::Init(PMESINIT pInit)
//{
//	m_sInit = *pInit;
//	g_This = this;
//	if (!ReadParam())
//	{
//		return FALSE;
//	}
//	m_pSoapMesLog->SetSaveDay(m_nLogSaveDays);
//	
//
//
//	m_strIP = GetPrivateProfileCString("Server","IP","",m_strConfigFile);	//http
//	m_nPort = GetPrivateProfileInt("Server","Port",0,m_strConfigFile);
//	m_nType = GetPrivateProfileInt("Set","Type",0,m_strConfigFile);
//	m_strUserID = GetPrivateProfileCString("Device","User","",m_strConfigFile);  //ftp
//	m_strPwd = GetPrivateProfileCString("Device","Pwd","",m_strConfigFile);
//	m_strFtpAddr = GetPrivateProfileCString("Server","FtpAddr","",m_strConfigFile);
//	m_nType = m_nType&m_useMes;
//	PlantArea= GetPrivateProfileInt("Set", "PlantArea", 0, m_strConfigFile);
//	
//	CMesGSoap::getInstance().setInfo(m_cstrUserName,m_cstrUserPassword,m_cstrOperatorID,m_cstrOperatorPassword,m_strEquipmentCode,m_cstrResourceCode);
//
//	SetMesAddrAndPort();
//
//	/*
//
//	std::string strMessage1,strMessage2;
//
//	char* strP1,strP2;
//
//	CString strAdress1,strAdress2;
//
//	CString str1,str2;
//
//	strAdress1.Format(_T("%p"),strMessage1);
//
//	strAdress2.Format(_T("%p"),strMessage2);
//
//	std::string strMessageT1,strMessageT2;
//
//	int iRet1,iRet2;
//
//	iRet1 = GetRequestRecipes(strMessage1);
//	
//	std::wstring wstrMessage;
//
//	CString cstrRecipe;
//
//	cstrRecipe.Format(_T("LineCode=%s&SectionCode=%s&EquipmentCode=%s&RecipeCode=CE01&Version=0.1.0"),
//		m_strLineCode,m_strSectionCode,m_strEquipmentCode);
//
//	iRet2 = GetRequestRecipeParameters(cstrRecipe,strMessage2);
//
//	strMessageT1 = Utf8ToAscii(strMessage1);
//
//	strMessageT2 = Utf8ToAscii(strMessage2);
//
//	str1.Format(_T("%s"),strMessageT1.c_str());
//
//	str2.Format(_T("%s"),strMessageT2.c_str());
//
//	neb::CJsonObject JsonRecipes(strMessage1);
//
//	neb::CJsonObject JsonRecipeParameters(strMessage2);
//
//	neb::CJsonObject JsonRecipesT1(strMessageT1);
//
//	neb::CJsonObject JsonRecipesT2(strMessageT2);
//
//	int iNum1 = JsonRecipes.GetArraySize();
//
//	int iNum2 = JsonRecipeParameters.GetArraySize();
//
//	int iNumT1 = JsonRecipesT1.GetArraySize();
//
//	int iNumT2 = JsonRecipesT2.GetArraySize();
//
//	neb::CJsonObject* pJsonRecipe = new neb::CJsonObject[iNum1];
//
//	for (int i = 0 ; i < iNum1 ;i++)
//	{
//		JsonRecipes.Get(i,pJsonRecipe[i]);
//		
//		std::string strRecipeCode,strProductCode,strVersion,strLineCode,strSection,strEquipmentCode;
//
//		pJsonRecipe[i].Get("RecipeCode",strRecipeCode);
//
//		pJsonRecipe[i].Get("ProductCode",strProductCode);
//
//		pJsonRecipe[i].Get("Version",strVersion);
//
//		pJsonRecipe[i].Get("LineCode",strLineCode);
//
//		pJsonRecipe[i].Get("SectionCode",strSection);
//
//		pJsonRecipe[i].Get("EquipmentCode",strEquipmentCode);
//			
//			//"RecipeCode": "CE01",
//			//"ProductCode": "CE01",
//			//"Version": "0.0.1",
//			//"LineCode": "线体1",
//			//"SectionCode": "工序1",
//			//"EquipmentCode": "设备1",
//			
//	}
//	
//	*/
//
//	CreateMessageQueue(&m_hvQueue);//创建一个IO队列
//	SetMessageQueueParam(m_hvQueue,"max_message_num",25);
//	HDevThreadContext Context;
//	HDevThread* pThread = new HDevThread(Context,
//		(void*)_Thread,0,0);//开启一个具有2个输入的线程;
//	HTuple ProcThreads;
//	pThread->ParStart(&ProcThreads);
//
//	//该线程主程序启动后再启动
////	m_ThreadFtpUpload = AfxBeginThread((AFX_THREADPROC)ThreadFtpUpload,this);
//
////	AfxBeginThread((AFX_THREADPROC)ThreadOnInfo,this);
//
//	return TRUE;
//}
void CMes::SetMesAddrAndPort()
{
	CMesGSoap::getInstance().setMesAddrAndPort(m_strIP,m_nPort);
}
void* CMes::_Thread(void *hcthread)//io线程
{
	HDevThread*  hcppthread = (HDevThread*) hcthread;
	try
	{
		g_This->Loop();
		hcppthread->Exit();
		delete hcppthread;
	}
	catch(HException& e)
	{
		CString strException;
		strException.Format("io_thread出现异常\r\n异常信息%s  [ %s() ]",e.ErrorMessage().Text()
			,e.ProcName().Text());
		//g_This->m_sInit.pLogView->DoSomething("EXCEPTION",(LPSTR)(LPCSTR)strException,NULL);
		bool is_direct_call = hcppthread->IsDirectCall();
		hcppthread->Exit();
		delete hcppthread;
		if (is_direct_call)
			throw e;
	}
	return NULL;
}

int CMes::DoSomething(void* message,void* wParam,void* lParam)
{
	CString strMessage;
	strMessage.Format("%s",(char*)message);
	if ("USEMES" == strMessage)
	{
		m_useMes = *(int*)wParam;

		m_nType = m_useMes;
	}
	if ("ONLINEINFO" == strMessage )
	{
		int *pRet = (int*)lParam;

		*pRet = m_iConnectStauts;

		return TRUE;
	}
	if ("INITIALIZE" == strMessage)
	{
		//return Init((PMESINIT)wParam);
		ReadParam();
		return TRUE;
	}
	if (0 == m_useMes)
	{
		return FALSE;
	}
	if ("PUSH_MESSAGE" == strMessage)
	{
		return PushMessage(*(HTuple*)wParam);
	}else if ("SHOW" == strMessage)
	{
		return DisplayMesSet();
	}
	else if ("STARTTHREAD" == strMessage)
	{
		return StartThread();
	}
	else if ("BATCH" == strMessage)
	{
		CString strBatch;
		if (wParam)
		{
			strBatch.Format("%s",(char*)wParam);
		}
		
		return Batch(strBatch);
	}
	else if ("RECIPEINFO" == strMessage)		//更新化配方版本信息
	{
		if (wParam)
		{
			return UpdateRecipeInfo((PRECIPEINFO)wParam);
		}
		else
		{
			return FALSE;
		}
	}
	else if ("INITRECIPE" == strMessage )			//初始化配方版本信息
	{
		if(wParam)
		{
			CString cstrRecipePath;

			cstrRecipePath.Format(_T("%s"),(char*)wParam);

			return InitRecipe(cstrRecipePath);
		}
		else
		{
			return FALSE;
		}
	}
	else if ("REPORTCOUNTINFO" == strMessage )
	{
		
		if (wParam)
		{
			CLockHelper lockHelp(&m_csSoapProcessParam);
			CString cstrLParam;

			cstrLParam.Format("%s",(char*)lParam);

			if ("DEFECT" == cstrLParam)
			{
				s_Count* pCount = (s_Count*)wParam;
				if (FALSE)
				{
					return  ReportDefectCountInfo(*(s_Count*)wParam);
				}
				else
				{
					return Soap_DefectCountInfo(*(s_Count*)wParam);
				}
			}
			if ("SIZE" == cstrLParam)
			{
				s_Count_Size* pCount = (s_Count_Size*)wParam;
				if(FALSE)
				{
					return  ReportSizeCountInfo(*(s_Count_Size*)wParam);
				}
				else
				{
					return Soap_SizeCountInfo(*(s_Count_Size*)wParam);
				}
				
			}

			if("TATOLCOUNT" == cstrLParam)
			{
				if (FALSE)
				{
					return ReportCountInfo(*(Total_Count *)wParam);
				}
				else
				{
					return Soap_CountInfo(*(Total_Count *)wParam);
				}
				
			}
			
		}
	}else if("CHECKRECIPEVERSION" == strMessage)
	{
		int  pRet=0;
		
		CString * pCstrResponse = (CString*)wParam;
		RECIPEINFO  *cstrSendData = (RECIPEINFO*)lParam;
		m_cstrSendData = *cstrSendData;
		std::string strResponse;	//返回值
		if (TRUE)
		{
			pRet = CHeckPrecipeVersion(strResponse);		//返回200 表示校验成功
		}
		else
		{
			pRet = Soap_CheckRecipeVersion(strResponse);		//返回200 表示校验成功
		}
	
		(*pCstrResponse).Format(_T("%s"),strResponse.c_str());

		return TRUE;
	}
	else if ("Send" == strMessage)
	{
		
		return TRUE;
	}
	else if ("EXIT" == strMessage)
	{
		m_bExit = *(BOOL*)wParam;

		return TRUE;
	}

	return FALSE;
}

int CMes::PushMessage(const HTuple& hvMessageSend)//放置消息进入队列
{
	if(!m_nType) return FALSE;
	try
	{
		EnqueueMessage(m_hvQueue, hvMessageSend, HTuple(), HTuple());//将消息投递到剔废车间
	}catch(HException& e)
	{
		if (H_ERR_MQOVL == e.ErrorCode())
		{
			CString strException;
			strException.Format("Mse队列已满,整合线程已退出,请排查原因");
			//m_sInit.pLogView->DoSomething("EXCEPTION",(LPSTR)(LPCSTR)strException,NULL);
		}else
		{
			throw e;
		}
		return FALSE;
	}
	return TRUE;
}

void CMes::Loop()
{
	//初始化
	if (0 == m_nType) return;
	//OpenSocket();

	HTuple hv_MessageRecv,hv_StopProcInfo,hv_TimeStart,hv_TimeEnd,hv_ErrorFlag;
	
	HTuple hv_Queue = m_hvQueue;//队列句柄，类似于指针的东西， hvQueue、m_hvQueue指向同一块数据
	while(TRUE)
	{
		
		DequeueMessage(hv_Queue, "timeout","infinite", &hv_MessageRecv);
		GetMessageParam(hv_MessageRecv, "key_exists", "stop_processing", &hv_StopProcInfo);
		if (0 != (HTuple(hv_StopProcInfo[0])))
		{
			break;
		}
		CountSeconds(&hv_TimeStart);//开始计时

		C_ALLOCATORWORKSHOPOUTPUT Output;

		try
		{
			Output.ReadMessage(hv_MessageRecv);





		}catch(HException& e)
		{

		}
		
		

//		UploadResultFileToMES();
	}
}

BOOL CMes::OpenSocket()
{
	CString strProtocol = "TCP";
	int nTimeOut = 30.0;
	try
	{
		try
		{
			CloseSocket(m_hv_SocketHandle);
		}catch(HException){}
		OpenSocketConnect(HTuple(m_strIP),m_nPort,(HTuple("protocol")).Append("timeout"),(HTuple(strProtocol)).Append(nTimeOut),&m_hv_SocketHandle);
		SetSocketParam(m_hv_SocketHandle,"timeout",10);	
		m_bConnected = TRUE;
	}catch(HException& e)
	{
		CString strMss;
		strMss.Format("socket无法连接Mes系统:%d  %s",e.ErrorCode(),e.ErrorMessage().Text());
		//m_sInit.pLogView->DoSomething("EXCEPTION",(void*)(LPCSTR)strMss,NULL);
		m_bConnected = FALSE;
		return FALSE;
	}
	return TRUE;
}

BOOL CMes::UploadResultFileToMES()
{
	//要实现的逻辑，遍历出所有的结果文件，忽略已经上传过的文件，没有上传过的就上传至MES服务器特定路径
	//已经上传过的文件名记录下来，便于后续对比有没有上传过

	return TRUE;
}

int CMes::MESRequest(CString& strData,eHttpAPI eApi)	//创建HTTP地址
{
	CString strUrl;
//	strUrl.Format("http://%s:%d/%s/ccd/ccd",m_strIP,m_nPort,g_strAPIFuncName[eApi]);
	strUrl.Format("http://%s:%d/api/edc/%s",m_strIP,m_nPort,g_strAPIFuncName[eApi]);
	std::string strRespons;			//返回错误信息
	return http_request(LPCSTR(strUrl),strRespons,(std::string)strData.GetString());
}
int CMes::MESRequest(CString& strData, std::string& strRespons ,eHttpAPI eApi)
{
	CString strUrl;
	
	if (m_cstrSendData.nType == 1)
	{
		strUrl.Format("http://%s:%d/linkmes-eip/api/Heartbeat", m_cstrSendData.IP,m_cstrSendData.Port);
	}
	else if (m_cstrSendData.nType == 2)
	{
		strUrl.Format("http://%s:%d/linkmes-eip/api/StateAndStopReasonUpload", m_cstrSendData.IP, m_cstrSendData.Port);
	}
	else if (m_cstrSendData.nType == 3)
	{
		strUrl.Format("http://%s:%d/linkmes-eip/api/AlarmUpload", m_cstrSendData.IP, m_cstrSendData.Port);
	}
	else if (m_cstrSendData.nType == 4)
	{
		
		strUrl.Format("http://%s:%d/linkmes-eip/api/ProcessDataUpload", m_cstrSendData.IP, m_cstrSendData.Port);
	}
	else if (m_cstrSendData.nType == 5)
	{
		strUrl.Format("http://%s:%d/linkmes-eip/api/File_PathUpload", m_cstrSendData.IP, m_cstrSendData.Port);
	}
	//strUrl.Format("http://mes-ht.naradapower.com/narada-mes-ht/mes/deviceData/dxTestDataUpload");
	
//	strUrl.Format("http://%s:%d/api/edc/",m_strIP,m_nPort);

	return http_request(LPCSTR(strUrl),strRespons,(std::string)strData.GetString());
}

int CMes::http_request(const char* url, std::string& strResponse, const std::string postdata, const char* headers, bool bReserveHeaders, int timeout)
{
	timeout = m_cstrSendData.OutTime;
	CURLcode res;
	CURL* curl = curl_easy_init();
	char chout[1024*50];

	memset(chout,0,1024*50);

	if (NULL == curl) return false;

	curl_easy_setopt(curl, CURLOPT_URL, url);

	//响应结果中保留头部信息
	if (bReserveHeaders)
		curl_easy_setopt(curl, CURLOPT_HEADER, 1);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_callback);//设置回调函数
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, chout);//设置写数据  chout   (void*)&strResponse
	curl_easy_setopt(curl, CURLOPT_POST, 1);

	//设置超时时间
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);

	//添加自定义头信息
	if (headers != NULL)
	{
		struct curl_slist *chunk = NULL;        
		chunk = curl_slist_append(chunk, headers);      
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
	}

	//设置发送消息
	if (postdata != "")
	{
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, postdata.size());
	}

	res = curl_easy_perform(curl);
	int nCode = 0;
	if (res == CURLE_OK)
		res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &nCode);
	else
		nCode = res;	// nCode = 0;

	strResponse = chout;

	curl_easy_cleanup(curl);

	return nCode;
}


int CMes::GetRequestRecipes(/*CString strUrl,*/std::string &strRespons)
{
	CString strUrl;

	strUrl.Format(_T("http://%s:%d/api/edc/reciperequest?LineCode=%s&SectionCode=%s&EquipmentCode=%s"),m_strIP,m_nPort,m_strLineCode,m_strSectionCode,m_strEquipmentCode);

	return http_getquest(LPCSTR(strUrl),strRespons);
}

int CMes::GetRequestRecipeParameters(CString const &strRecipe,std::string &strRespons)
{
	CString strUrl;

	strUrl.Format(_T("http://%s:%d/api/edc/recipeparameterrequest?%s"),m_strIP,m_nPort,strRecipe);

	return http_getquest(LPCSTR(strUrl),strRespons);
}

int CMes::http_getquest(const char* url, std::string& strResponse, const char* headers, bool bReserveHeaders, int timeout)
{
	CURLcode res;

//	curl_global_init(CURL_GLOBAL_ALL);

	CURL* curl = curl_easy_init();

	 struct MemoryStruct MemoryChunk;

	 MemoryChunk.memory = (char*)malloc(1);  /* will be grown as needed by the realloc above */ 
	
	 MemoryChunk.size = 0;    /* no data at this point */ 

	if (NULL == curl)
		{
			curl_easy_cleanup(curl);

//			curl_global_cleanup();

			return false;
		}

	curl_easy_setopt(curl, CURLOPT_URL, url);

	//响应结果中保留头部信息
	if (bReserveHeaders)
		{
			curl_easy_setopt(curl, CURLOPT_HEADER, 1);
		}

	curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);				//

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);//设置回调函数

	curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&MemoryChunk);//设置写数据	//chout		(void*)&strResponse

	curl_easy_setopt(curl, CURLOPT_POST, 0);			//http   Get  ,post 设为1

	//设置超时时间
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);

	//添加自定义头信息
	if (headers != NULL)
	{
		struct curl_slist *chunk = NULL;        
		chunk = curl_slist_append(chunk, headers);      
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
	}

	res = curl_easy_perform(curl);

	int nCode = 0;

	if (res == CURLE_OK)		//查询错误码
		res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &nCode);
	else
		nCode = res;



	strResponse = MemoryChunk.memory;

	curl_easy_cleanup(curl);

	free(MemoryChunk.memory);

//	curl_global_cleanup();

	return nCode;
}



size_t CMes::WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *stream) 
{

	size_t realsize = size * nmemb;

	struct MemoryStruct *mem = (struct MemoryStruct *)stream;

	char *ptr1 = (char*)realloc(mem->memory, mem->size + realsize + 1);
	if(ptr == NULL) {
		/* out of memory! */ 
	//	printf("not enough memory (realloc returned NULL)\n");
		return 0;
	}

	mem->memory = ptr1;
	memcpy(&(mem->memory[mem->size]), ptr, realsize);
	mem->size += realsize;
	mem->memory[mem->size] = 0;

	return realsize;





	/*

	std::string data((const char*) ptr, (size_t) size * nmemb);

	data = Utf8ToAscii(data);

	strcpy((char*)stream,data.c_str());

	return size * nmemb;

	*/


/*
	if (stream == NULL || ptr == NULL || size == 0)
		 return 0;
	  
	size_t realsize = size * nmemb;

	std::string *buffer = (std::string*)stream;

	if (buffer != NULL)
		{
			buffer->append((const char *)ptr, realsize);

			*buffer = Utf8ToAscii(*buffer);
		}
	 return realsize;
	*/
}

size_t CMes::write_data_callback(void *ptr, size_t size, size_t nmemb, void *stream) 
{
	std::string data((const char*) ptr, (size_t) size * nmemb);

	data = Utf8ToAscii(data);

	strcpy((char*)stream,data.c_str());

	return size * nmemb;
}

int CMes::FtpUploadFile(CString & strFullFilePath)
{
	int nRet = 0;

	CString strServerFilePath;

	if (!LocalFilePathToServerFilePath(strFullFilePath,strServerFilePath,m_strRootPathSymbol))
	{
		nRet = -2;	//文件路径转换错误
	}
	nRet = FtpUpload(strServerFilePath,strFullFilePath/*本地路径*/);  //C:\Users\xuxh\Desktop\111\0.bmp

	if ( nRet ==0  )
	{

		//std::string strResponse;	//返回值	
		//neb::CJsonObject cJsonSend;
		//neb::CJsonObject cJsonSendList;
		//neb::CJsonObject cJsonSendListValue[5];
		//neb::CJsonObject cJsonSendValue;
		//CString cstrTimeStamp, cstrMessage;
		//std::string strSendMessage, strSendUTF8, strRespon;
		//SYSTEMTIME m_tNow;
		//GetLocalTime(&m_tNow);
		//CString  m_cstrNow;
		//m_cstrNow.Format("%04d/%02d/%02d %02d:%02d:%02d", m_tNow.wYear, m_tNow.wMonth, m_tNow.wDay, m_tNow.wHour, m_tNow.wMinute, m_tNow.wSecond);
		//cJsonSend.Add("EquipPC_ID", std::string(m_cstrSendData.FactoryCode.GetString()));
		//cJsonSend.Add("EquipPC_Password", std::string(m_cstrSendData.TestCode.GetString()));
		//cJsonSend.Add("Equip_Code", std::string(m_cstrSendData.EquipmentCode.GetString()));
		//cJsonSend.Add("Upload_Time", std::string(m_cstrNow.GetString()));
		//CString strFileName;
		//strFileName = strFullFilePath.Right(strFullFilePath.GetLength() - strFullFilePath.ReverseFind('\\') - 1);
		//CString strData;
		//cJsonSend.AddEmptySubArray("ProductList");
		//cJsonSendValue.Add("WIP_Code", "");
		//cJsonSendValue.Add("Passed", "0");
		//cJsonSendValue.Add("File_Path", std::string(strServerFilePath.GetString()));
		//cJsonSendValue.Add("File_Name", std::string(strFileName.GetString()));
		//cJsonSendValue.Add("Collect_Time", std::string(m_cstrNow.GetString()));

		//cJsonSend["ProductList"].Add(cJsonSendValue);
		//strSendMessage = cJsonSend.ToString();

		//strSendUTF8 = AsciiToUtf8(strSendMessage);

		//MESRequest((CString)strSendUTF8.c_str(), strRespon, CheckEquipmentRecipeVersion);
		//CString Message;
		//Message.Format("Res: %s  Send: %s", strRespon.c_str(), strSendMessage.c_str());
		//m_pSoapMesLog->UploadFileLog(Message);

		try
		{
			if (strFullFilePath.Find("FTPC") >= 0)
			{
				CString strException;
				CString strFileName1, strFileName2;
				strFileName1 = strFullFilePath;
				strFileName1.Replace("FTPC", "");
				/*::CopyFile(filename, strFileName1, TRUE);
				::DeleteFileA(filename);*/
				strFileName1.Replace("\\", "/");
				strFullFilePath.Replace("\\", "/");
				if (PathFileExists(strFullFilePath))
				{
					CStdioFile recordFile;
					if (recordFile.Open(strFullFilePath, CFile::modeReadWrite | CFile::typeBinary | CFile::shareDenyNone | CFile::modeCreate | CFile::modeNoTruncate))
					{
						recordFile.Close();
					
						if (!PathFileExists(strFileName1))
						{
							if (!PathFileExists(strFileName1))
							{
								CFile::Rename(strFullFilePath, strFileName1);
							}
							else
							{
								HTuple hv_path;
								hv_path = (HTuple)strFullFilePath;
								DeleteFile(hv_path);
							}
						}
						
					}
					
				}
								
			}
			if (strFullFilePath.Find("_NG_") >= 0)
			{
				CString strException;
				CString strFileName1, strFileName2;
				strFileName1 = strFullFilePath;
				strFileName1.Replace("_NG_", "_G_");
				/*::CopyFile(filename, strFileName1, TRUE);
				::DeleteFileA(filename);*/
				strFileName1.Replace("\\", "/");
				strFullFilePath.Replace("\\", "/");
				if (PathFileExists(strFullFilePath))
				{
					if (!PathFileExists(strFileName1))
					{
						CFile::Rename(strFullFilePath, strFileName1);
					}
					else
					{
						HTuple hv_path;
						hv_path = (HTuple)strFullFilePath;
						DeleteFile(hv_path);
					}
					
				}
				
			}
		}
		catch (const std::exception&)
		{

		}
		
		

	}

	if (m_isSendHttpMSG)
	{
		if (FALSE)			//1期
		{
			MesReportFileUploadCompleted(strServerFilePath);
		}
		if(FALSE)			//2期
		{
		//	const std::vector<ParamCCDUploadFile> & vecParamCCDUpload,neb::CJsonObject & nebCJsonReciev
			if (PlantArea == 1)
			{

			}
			else
			{
				std::vector<ParamCCDUploadFile> vecParamCCDUpload;
				GetParamCCDUploadFiles(strServerFilePath, vecParamCCDUpload);
				Soap_CCDFileUploadComplete(vecParamCCDUpload, neb::CJsonObject());
			}
		
		}
		
	}

	return nRet;
}

int CMes::FtpUpload(CString& strRemoteFilePath,CString& strLocalFilePath)
{
	int iRet = -1;

	CString cstrStatus, cstrMessage;
	std::string strPath = strRemoteFilePath.GetString();
	std::string strPathUtf8 = AsciiToUtf8(strPath);
	strPathUtf8 = Utf8ToGBK(strPathUtf8);
	
	iRet = ftp_upload(strPathUtf8.c_str(),LPCSTR(strLocalFilePath),LPCSTR(m_strUserID),LPCSTR(m_strPwd));

	if(0 != iRet)		//失败重新上传
	{
		Sleep(200);

		iRet = ftp_upload(strPathUtf8.c_str(),LPCSTR(strLocalFilePath),LPCSTR(m_strUserID),LPCSTR(m_strPwd));
	}

	//if (0 == iRet)
	//{
	//	cstrStatus.Format(_T("TRUE"));

	//	AppendUploadTuple(strLocalFilePath);		//记录已上传文件
	//}
	//else
	//{
	//	cstrStatus.Format(_T("FALSE"));
	//}
	
	cstrMessage.Format(_T("ftp_upload:%s\t状态码:%d\t上传文件:%s"),cstrStatus,iRet,strLocalFilePath);
	m_pSoapMesLog->UploadFileLog(cstrMessage);


	if (0 == iRet && m_bRename)
	{
		RenameFile(strLocalFilePath,m_strRenameSymbol);
	}

	return iRet;


}

int CMes::ftp_upload(const char *remote_file_path,const char *local_file_path,const char *username,const char *password,long timeout, long tries)
{
    // init curl handle
 //   curl_global_init(CURL_GLOBAL_ALL);

    CURL *curlhandle = curl_easy_init();

    // get user_key pair
    char user_key[1024] = {0};
    sprintf(user_key, "%s:%s", username, password);

    FILE *file;
    long uploaded_len = 0;
    CURLcode ret = CURLE_GOT_NOTHING;
    file = fopen(local_file_path, "rb");
    if (file == NULL) 
    {
        perror(NULL);
        return 0;
    }
	//获取源文件大小
	fseek(file, 0, SEEK_END);
	int resource_file_size = ftell(file);

	curl_easy_setopt(curlhandle, CURLOPT_URL, remote_file_path);
	curl_easy_setopt(curlhandle, CURLOPT_USERPWD, user_key);
	curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 1);
	if (timeout)
		curl_easy_setopt(curlhandle, CURLOPT_FTP_RESPONSE_TIMEOUT, timeout);
	curl_easy_setopt(curlhandle, CURLOPT_READDATA, file); //没有专门写读源文件回调函数，CURLOPT_READDATA会自动读取
	curl_easy_setopt(curlhandle, CURLOPT_UPLOAD, 1);
	curl_easy_setopt(curlhandle, CURLOPT_INFILESIZE, resource_file_size);
	curl_easy_setopt(curlhandle, CURLOPT_FTP_CREATE_MISSING_DIRS, 1);

    // upload: 断点续传
    for (int c = 0; (ret != CURLE_OK) && (c < tries); c++)
    {
        /* are we resuming? */
        if (c)
        { /* yes */
            /* determine the length of the file already written */
            /*
            * With NOBODY and NOHEADER, libcurl will issue a SIZE
            * command, but the only way to retrieve the result is
            * to parse the returned Content-Length header. Thus,
            * getContentLengthfunc(). We need discardfunc() above
            * because HEADER will dump the headers to stdout
            * without it.
            */
            curl_easy_setopt(curlhandle, CURLOPT_NOBODY, 1L);
            curl_easy_setopt(curlhandle, CURLOPT_HEADER, 1L);
            ret = curl_easy_perform(curlhandle);
            if (ret != CURLE_OK)
                continue;
            curl_easy_setopt(curlhandle, CURLOPT_NOBODY, 0L);
            curl_easy_setopt(curlhandle, CURLOPT_HEADER, 0L);
            fseek(file, uploaded_len, SEEK_SET);
            curl_easy_setopt(curlhandle, CURLOPT_APPEND, 1L);
        }
        else
            curl_easy_setopt(curlhandle, CURLOPT_APPEND, 0L);

        ret = curl_easy_perform(curlhandle);
    }
    
	fclose(file);
    // exit curl handle
    curl_easy_cleanup(curlhandle);

//    curl_global_cleanup();

    return ret;
}

double CMes::GetFtpFileLength(CString& strFtpFilePath)
{  
	char* url = (LPSTR)(LPCTSTR)strFtpFilePath;
	double dFileLenth = 0;
	CURL *handle = curl_easy_init();  
	curl_easy_setopt(handle, CURLOPT_URL, url);
	curl_easy_setopt(handle, CURLOPT_USERPWD, (LPSTR)(LPCTSTR)(m_strUserID+":"+m_strPwd));
	curl_easy_setopt(handle, CURLOPT_HEADER, 1);    //只需要header头  
	curl_easy_setopt(handle, CURLOPT_NOBODY, 1);    //不需要body
	if (curl_easy_perform(handle) == CURLE_OK)
	{  
		if (curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &dFileLenth) != CURLE_OK)
		{
			dFileLenth = -1;  
		}
	} else 
	{  
		dFileLenth = -1;  
	}
	curl_easy_cleanup(handle);
	return dFileLenth;  
}

double CMes::GetLocalFileLength(CString& strLocalFilePath)
{
	
	double dLength=0;
	//获取文件长度

	return dLength;
}

BOOL CMes::ReadParam(void)
{
	m_strConfigFile.Format("%s/Config/SCIMES/MES.ini",GetCurrentAppPath());
	if (!PathFileExists(m_strConfigFile))
	{
		AfxMessageBox("SCIMES:MES配置文件不存在");
		return FALSE;
	}
	m_strIP = GetPrivateProfileCString("ServerFTP","IP","",m_strConfigFile);	//http
	m_nPort = GetPrivateProfileInt("ServerFTP","Port",0,m_strConfigFile);
	m_nType = GetPrivateProfileInt("Set","Type",0,m_strConfigFile);
	m_nLogType = GetPrivateProfileInt("Set","nLogType",1,m_strConfigFile);
	m_strUserID = GetPrivateProfileCString("ServerFTP","User","",m_strConfigFile);  //ftp
	m_strPwd = GetPrivateProfileCString("ServerFTP","Pwd","",m_strConfigFile);
	m_strFtpAddr = GetPrivateProfileCString("ServerFTP","FtpAddr","",m_strConfigFile);
	m_strLineCode = GetPrivateProfileCString("EquipmentInfo","LineCode","",m_strConfigFile);
	m_strSectionCode = GetPrivateProfileCString("EquipmentInfo","SectionCode","",m_strConfigFile);
	m_strEquipmentCode = GetPrivateProfileCString("EquipmentInfo","EquipmentCode","",m_strConfigFile);
	m_strEquipmentName = GetPrivateProfileCString("EquipmentInfo","EquipmentName","",m_strConfigFile);
	m_strFactory = GetPrivateProfileCString("EquipmentInfo","Factory","",m_strConfigFile);
	m_strEQM = GetPrivateProfileCString("EquipmentInfo","EQM","",m_strConfigFile);
	m_cstrResourceCode = GetPrivateProfileCString("EquipmentInfo","ResourceCode","",m_strConfigFile);
	m_cstrUserName = GetPrivateProfileCString("EquipmentInfo","UserName","",m_strConfigFile);
	m_cstrUserPassword = GetPrivateProfileCString("EquipmentInfo","UserPassword","",m_strConfigFile);
	m_cstrOperatorID = GetPrivateProfileCString("EquipmentInfo","OperatorID","",m_strConfigFile);
	m_cstrOperatorPassword = GetPrivateProfileCString("EquipmentInfo","OperatorPassword","",m_strConfigFile);


	
	m_strLocalFilePath = GetPrivateProfileCString("Path","LocalImagePath","",m_strConfigFile);
	m_strServerFilePath = GetPrivateProfileCString("Path","ServerResultPath","",m_strConfigFile);
	m_isSendHttpMSG = GetPrivateProfileInt("SendSet","SendHttpMSG",0,m_strConfigFile);
	m_intervalMinute = GetPrivateProfileInt("SendSet","IntervalMinute",5,m_strConfigFile);
	m_iThreadNumber = GetPrivateProfileInt("SendSet","threadNumber",1,m_strConfigFile);
	m_bSendOK = GetPrivateProfileInt("SendSet","bSendOK",0,m_strConfigFile);
	m_bSendNG = GetPrivateProfileInt("SendSet","bSendNG",0,m_strConfigFile);
	m_bSendNGCrop = GetPrivateProfileInt("SendSet","bSendNGCrop",0,m_strConfigFile);
	m_bSendCover = GetPrivateProfileInt("SendSet","bSendCover",0,m_strConfigFile);
	m_bRename = GetPrivateProfileInt("SendSet","bRename",0,m_strConfigFile);
	m_strLocalRootPath  = GetPrivateProfileCString("SendSet","LocalRootPath","",m_strConfigFile);
	m_strRootPathSymbol = GetPrivateProfileCString("SendSet","RootPathSymbol","History/",m_strConfigFile);
	m_strRenameSymbol = GetPrivateProfileCString("SendSet","RenameSymbol","-Upload",m_strConfigFile);
	m_strLocalRootPathP = GetPrivateProfileCString("SendSet", "LocalRootPathP", "", m_strConfigFile);
	m_strRecipeCode = GetPrivateProfileCString("RecipeInfo","RecipeCode","",m_strConfigFile);

	m_strProductCode = GetPrivateProfileCString("RecipeInfo","ProdctCode","",m_strConfigFile);

	m_strRecipeVison = GetPrivateProfileCString("RecipeInfo","RecipeVison","",m_strConfigFile);

	
	/*try
	{
		m_cstrUploadTuple.Format("%s/UploadFile.tup",m_strLocalRootPath);

		ReadTuple(HTuple(m_cstrUploadTuple), &m_hvUploaded);
	}
	catch(...)
	{
		m_hvUploaded.Clear();

		CString strMsg;

		strMsg.Format("读取%s异常\t",m_cstrUploadTuple);

		m_record.writeMSG(strMsg);

	}
	m_record.m_nLogType = m_nLogType;*/

	return TRUE;
}


BOOL CMes::DisplayMesSet(void)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());
	CDlgMesSet dlg;
	dlg.m_RealMes = this;
	dlg.DoModal();
	return TRUE;
}


BOOL CMes::WriteParam(void)
{
	try
	{
		CMesGSoap::getInstance().setInfo(m_cstrUserName,m_cstrUserPassword,m_cstrOperatorID,m_cstrOperatorPassword,m_strEquipmentCode,m_cstrResourceCode);
		WritePrivateProfileInt("Set","Type",m_nType,m_strConfigFile);
		

		WritePrivateProfileString("Server","IP",m_strIP,m_strConfigFile);	//http
		WritePrivateProfileInt("Server","Port",m_nPort,m_strConfigFile);

		WritePrivateProfileString("Device","User",m_strUserID,m_strConfigFile);  //ftp
		WritePrivateProfileString("Device","Pwd",m_strPwd,m_strConfigFile);
		WritePrivateProfileString("Server","FtpAddr",m_strFtpAddr,m_strConfigFile);

		WritePrivateProfileInt("Set","nLogType",m_nLogType,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","LineCode",m_strLineCode,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","SectionCode",m_strSectionCode,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","EquipmentCode",m_strEquipmentCode,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","EquipmentName",m_strEquipmentName,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","OperatorID",m_cstrOperatorID,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","OperatorPassword",m_cstrOperatorPassword,m_strConfigFile);

		WritePrivateProfileString("EquipmentInfo","Factory",m_strFactory,m_strConfigFile);
//		WritePrivateProfileString("EquipmentInfo","Process",m_strProcess,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","EQM",m_strEQM,m_strConfigFile);
//		WritePrivateProfileString("EquipmentInfo","Equipment",m_strEquipment,m_strConfigFile);

		WritePrivateProfileString("EquipmentInfo","ResourceCode",m_cstrResourceCode,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","UserName",m_cstrUserName,m_strConfigFile);
		WritePrivateProfileString("EquipmentInfo","UserPassword",m_cstrUserPassword,m_strConfigFile);
		WritePrivateProfileInt("LogPath","LogSaveDays",m_nLogSaveDays,m_strConfigFile);

		WritePrivateProfileInt("SendSet","SendHttpMSG",m_isSendHttpMSG,m_strConfigFile);

		WritePrivateProfileInt("SendSet","IntervalMinute",m_intervalMinute,m_strConfigFile);

		WritePrivateProfileInt("SendSet","bSendOK",m_bSendOK,m_strConfigFile);
		
		WritePrivateProfileInt("SendSet","bSendNG",m_bSendNG,m_strConfigFile);
		
		WritePrivateProfileInt("SendSet","bSendNGCrop",m_bSendNGCrop,m_strConfigFile);
		
		WritePrivateProfileInt("SendSet","bSendCover",m_bSendCover,m_strConfigFile);

		WritePrivateProfileInt("SendSet","bRename",m_bRename,m_strConfigFile);
		
		WritePrivateProfileString("SendSet","LocalRootPath ",m_strLocalRootPath,m_strConfigFile);
		
		WritePrivateProfileString("SendSet","RootPathSymbol  ",m_strRootPathSymbol,m_strConfigFile);
		
		WritePrivateProfileString("SendSet","RenameSymbol",m_strRenameSymbol,m_strConfigFile);

	}
	catch (CException* e)
	{
		return FALSE;
	}
	
	return TRUE;
}

BOOL CMes::GetSendFileJson(CString const & strFilePath, std::string & strSendJson, SYSTEMTIME const& iLocalTime)
{
	neb::CJsonObject oJsonPackage;

	neb::CJsonObject oJsonFile;

	CString strServerFilePath;

	CString strFileName;

	CString strFileType;

	CString strProductBarcode;

	CString strTimestamp;

	CString strIsOK = _T("");

	//	LocalFilePathToServerFilePath(strLocalFilePath,strServerFilePath);

	strServerFilePath = strFilePath;

	strFileType = strFilePath.Right(strFilePath.GetLength() - strFilePath.ReverseFind('.') - 1);

	strFileName = strFilePath.Right(strFilePath.GetLength() - strFilePath.ReverseFind('/') - 1);

	if (strFileName.Find('_') > 0)
	{
		strProductBarcode = strFileName.Left(strFileName.Find('_'));
	}
	else
	{
		strProductBarcode.Format(_T("33333"));
	}

	if (strFileType == "jpg" || strFileType == "bmp")
	{
		strIsOK.Format(_T("true"));
	}

	//2020-03-23T15:01:14.6810138+08:00
	strTimestamp.Format(_T("%04d-%02d-%02dT%02d:%02d:%02d.%03d+08:00"),
		iLocalTime.wYear,iLocalTime.wMonth,iLocalTime.wDay,iLocalTime.wHour,iLocalTime.wMinute,iLocalTime.wSecond,iLocalTime.wMilliseconds);

	oJsonFile.Add("FilePath",strServerFilePath.GetString());

	if (strIsOK != _T(""))
	{
		oJsonFile.Add("IsOk",strIsOK.GetString());
	}

	oJsonFile.Add("ProductBarcode",strProductBarcode.GetString());

	oJsonFile.Add("Timestamp",strTimestamp.GetString());

	oJsonPackage.AddEmptySubArray("Files");

	oJsonPackage["Files"].Add(oJsonFile);

	oJsonPackage.Add("LineCode",m_strLineCode.GetString());

	oJsonPackage.Add("SectionCode",m_strSectionCode.GetString());

	oJsonPackage.Add("EquipmentCode",m_strEquipmentCode.GetString());

	oJsonPackage.Add("Timestamp",strTimestamp.GetString());

	strSendJson.empty();

	strSendJson = "[" + oJsonPackage.ToString() + "]";

	return TRUE;
}


CString CMes::GetFtpAddr(void)
{
	return m_strFtpAddr;
}


int CMes::MESReportEquipmentOnlineInfo(CString& strData , std::string &strRespons)
{
	CString strUrl;

	strUrl.Format("http://%s:%d/api/edc/online",m_strIP,m_nPort);

	return http_request(LPCSTR(strUrl),strRespons,(std::string)strData.GetString());
}

int CMes::MESReportEquipmentRecipeParametersInfo(CString& strData,std::string &strRespons)
{
	CString strUrl;

	strUrl.Format("http://%s:%d/api/edc/recipeparameter",m_strIP,m_nPort);

	return http_request(LPCSTR(strUrl),strRespons,(std::string)strData.GetString(),"Content-Type:application/json;charset=UTF-8", false);
}

int CMes::MESReportCcdFilesUploadCompleted(CString& strData,std::string &strRespons)
{
	CString strUrl;
	strUrl.Format("http://%s:%d/api/ccd/ccd",m_strIP,m_nPort);
	return http_request(LPCSTR(strUrl),strRespons,(std::string)strData.GetString());
}

int CMes::MesReportFileUploadCompleted(CString & strFilePath)
{
	int iRet;

	CString strSendFilePath,strMessage;

	CString cstrTime;

	std::string strRespon;

	std::string strSendMessage;

	std::string strSendMessageUTF8;

	GetLocalTime(&m_currentTime);

	strSendFilePath.Format(_T("%s"),strFilePath);


	if (!GetSendFileJson(strSendFilePath,strSendMessage,m_currentTime))
	{
		iRet = -1;

		strMessage.Format(_T("MESReportCcdFilesUploadCompleted\tCJeson转换失败！\t%文件路径：%s"),strSendFilePath);

		m_record.writeHttpFile(strMessage);

		return iRet;
	}
	
	strSendMessageUTF8 = AsciiToUtf8(strSendMessage);

	iRet = MESReportCcdFilesUploadCompleted((CString)strSendMessageUTF8.c_str(),strRespon);

	if (200 != iRet)
	{
		strMessage.Format(_T("MESReportCcdFilesUploadCompleted;返回码：%d\t返回信息：%s\n发送信息：%s"),iRet,strRespon.c_str(),strSendMessage.c_str());

	//	m_sInit.pLogView->DoSomething("EXCEPTION", (void*)(LPCSTR)strMessage,NULL);

		Log(strMessage);

		m_record.writeHttpFile(strMessage);
	}

	strMessage.Format(_T("MESReportCcdFilesUploadCompleted;返回码：%d\t\n发送信息：%s"),iRet,strSendMessage.c_str());
	
	m_record.writeHttpFile(strMessage);


	return iRet;
}

int CMes::MESReportProcessingParameter(CString& strData,std::string &strRespons)
{
	CString strUrl;

	strUrl.Format("http://%s:%d/api/edc/productprocessingparameter",m_strIP,m_nPort);

	return http_request(LPCSTR(strUrl),strRespons,(std::string)strData.GetString(),"Content-Type:application/json;charset=UTF-8", false);
}

BOOL CMes::LocalFilePathToServerFilePath(CString const & strLocalFilePath, CString & strServerFilePath, CString const & strSymbol)
{
	//本地文件路径
	//Map/年/月/日/卷号/产品名称/正面/NG/WIP条码_（OK/NG）_yyyyMMddHHmmssfff.jpg；图片
	//Map/年/月/日/卷号/产品名称/WIP条码_yyyyMMddHHmmssfff.csv ；          结果文件
	//服务器文件路径
	//工厂/工序/设备厂家/设备编号/Data/年/月/日/WIP条码_yyyyMMddHHmmssfff.csv
	//工厂/工序/设备厂家/设备编号/Image/年/月/日/WIP条码_（OK/NG）_yyyyMMddHHmmssfff.jpg
	CString strRemoteFile;	//服务器文件路径
	CString strFileExtendName;	//文件扩展名
	CString strFileName;		//文件名，带扩展名
	CString strDate;			//截取时间路径
	CString strFileType;		//文件类型
	CString strBatc;		//当前文件卷号
	CString date;
	if (strLocalFilePath.Find("FTPC") >= 0 || strLocalFilePath.Find(_T("_NG_")) >= 0)
	{
		if (strLocalFilePath.Find("FTPC") >= 0)
		{
			date.Format("%s", "History\\");
			 
		}
		if (strLocalFilePath.Find(_T("_NG_")) >= 0)
		{
			date.Format("%s", "瑕疵\\");
		}
	}
	else
	{
		return FALSE;
	}
	if (/*m_sInit.nProductType ==*/ 1)		//瑕疵
	{
		strFileName = strLocalFilePath.Right(strLocalFilePath.GetLength()-strLocalFilePath.ReverseFind('\\')-1);

		strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.Find('.')-1);

		strDate = strLocalFilePath.Right(strLocalFilePath.GetLength()- strLocalFilePath.Find(date)- date.GetLength());

		strDate = strDate.Left(strDate.Find("日\\")+2);

		strBatc = strLocalFilePath.Right(strLocalFilePath.GetLength() - strLocalFilePath.Find(date) - date.GetLength());

		

		if (strFileExtendName == _T("csv") || strFileExtendName == _T("xls"))
		{
			strBatc = strBatc.Left(strBatc.Find(strFileName) - 1);
			strBatc = strBatc.Right(strBatc.GetLength() - strBatc.Find("日\\") - 3);
			strFileType.Format(_T("Data"));
		}
		else if (strFileExtendName == _T("jpg") || strFileExtendName == _T("bmp") || strFileExtendName == _T("png"))
		{
			strBatc = strBatc.Right(strBatc.GetLength() - strBatc.Find("日\\") - 3);
			strBatc = strBatc.Left(strBatc.Find("工位") - 1);
			strFileType.Format(_T("Image"));
		}
		else
		{
			strFileType.Format(_T("未知文件类型"));
		}
		//根地址 + 设备编号 + 数据类型 + 日期 + 文件名
		if (PlantArea == 1)
		{
			if (strFileExtendName == _T("csv") || strFileExtendName == _T("xls"))
			{
				strServerFilePath.Format(_T("%s/%s/%s/%s/%s/%s/%s"), GetFtpAddr(), m_strUserID, m_strEquipmentCode, strDate, strFileType, strBatc, strFileName);
				strServerFilePath.Replace("\\", "/");
			}
			else
			{
				strServerFilePath.Format(_T("%s/%s/%s/%s/%s/%s/%s"), GetFtpAddr(), m_strUserID, m_strEquipmentCode, strDate, strFileType, strBatc, strFileName);
				strServerFilePath.Replace("\\", "/");
			}
			
		}
		else
		{
			strServerFilePath.Format(_T("%s/%s/%s/%s/%s"), GetFtpAddr(),  strFileType, strDate, strBatc, strFileName);
			strServerFilePath.Replace("\\", "/");
		}
		
	}
	else if (false)		//尺寸
	{
		strFileName = strLocalFilePath.Right(strLocalFilePath.GetLength()-strLocalFilePath.ReverseFind('\\')-1);

		strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.Find('.')-1);

		strDate = strLocalFilePath.Right(strLocalFilePath.GetLength()- strLocalFilePath.Find(strSymbol)-strSymbol.GetLength());

		strDate = strDate.Left(strDate.Find("日\\")+2);

		strDate.Insert(strDate.Find(_T("年")) + 2,"\\");

		if (strFileExtendName == _T("csv") || strFileExtendName == _T("xls"))
		{
			strFileType.Format(_T("Data"));
		}
		else if (strFileExtendName == _T("jpg") || strFileExtendName == _T("bmp") || strFileExtendName == _T("png"))
		{
			strFileType.Format(_T("Image"));
		}
		else
		{
			strFileType.Format(_T("未知文件类型"));
		}
		//根地址 + 设备编号 + 数据类型 + 日期 + 文件名
		if (PlantArea == 1)
		{
			strServerFilePath.Format(_T("%s/%s/%s/%s/%s/%s"), GetFtpAddr(), m_strUserID, m_strEquipmentCode, strDate, strFileType,  strFileName);
			strServerFilePath.Replace("\\", "/");
		}
		else
		{
			strServerFilePath.Format(_T("%s/%s/%s/%s/%s"), GetFtpAddr(), m_strEquipmentCode, strFileType, strDate, strFileName);
			strServerFilePath.Replace("\\", "/");
		}
		
	}

	return TRUE;
}


BOOL CMes::DetermineSend(CString const& strLocalFilePath)
{
	BOOL bRet = TRUE;		//TRUE 发送，FALSE 不发送

	BOOL isSent = FALSE;

	CString strFileType;

	CString strFileName;

	CString strFileExtendName;

	strFileName = strLocalFilePath.Right(strLocalFilePath.GetLength()-strLocalFilePath.ReverseFind('\\')-1);

	strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.Find('.')-1);

	isSent = HasBeenSent(strLocalFilePath);

	if (!m_bSendCover && isSent)
	{
		bRet = FALSE;

		return bRet;
	}
	if (strFileExtendName == _T("bmp") || strFileExtendName == _T("jpg"))
	{
		int iOKImg = 0;

		int iNGImg = 0;

		int iNGCImg = 0;

		iOKImg = strFileName.Find(_T("_OK_"));

		iNGImg = strFileName.Find(_T("_NG_"));

		iNGCImg = strFileName.Find(_T("_NGC_"));

		if (iOKImg >= 0 && m_bSendOK)
		{
			bRet = TRUE;
		}
		else if (iNGImg >= 0 && m_bSendNG)
		{
			bRet = TRUE;
		}
		else if (iNGCImg >= 0 && m_bSendCover)
		{
			bRet  = TRUE;
		}
		else
		{
			bRet = FALSE;
		}
	}
	return bRet;
}

BOOL CMes::HasBeenSent(CString const& strLocalFilePath)//FALSE  未发送过，TRUE 已发送过
{
	BOOL bRet = FALSE;

	CString strFileName;

	strFileName = strLocalFilePath.Right(strLocalFilePath.GetLength()-strLocalFilePath.ReverseFind('\\')-1);

	if (strFileName.Find(m_strRenameSymbol) < 0)
	{
		bRet = FALSE;
	}
	else
	{
		bRet = TRUE;
	}
	return bRet;   //FALSE  未发送过，TRUE 已发送过
}


BOOL CMes::UNRename(CString & strFilePath)
{
	std::vector<CString>vecFileList;

	::GetFilePath(vecFileList,strFilePath);

	for (std::vector<CString>::iterator iter = vecFileList.begin(); iter != vecFileList.end(); iter++)
	{
		if (HasBeenSent(*iter))
		{
			CString strOldFilePath;

			UNRenameFile(*iter,m_strRenameSymbol,strOldFilePath);
		}		
	}
	return TRUE;
}


BOOL UNRenameFile(CString const & strLocalFilePath , CString const & strSymbol,CString& strOldFilePath)
{
	CString	strFullFilePath;	//带路径文件全名

	CString strFilePath;		//文件夹路径

	CString strFileExtendName;	//文件扩展名

	CString strFileName;		//文件名，带扩展名

	CString strFile;			//文件名，不带扩展名

	CString strNewFilePath;		//新文件 带路径全名

	CString strNewFile;			//新文件名

	strFullFilePath = strLocalFilePath;

	strFilePath = strFullFilePath.Left(strFullFilePath.ReverseFind('\\')+1);

	strFileName = strFullFilePath.Right(strFullFilePath.GetLength()-strFullFilePath.ReverseFind('\\')-1);

	strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.ReverseFind('.')-1);

	strFile = strFileName.Left(strFileName.Find('.'));

	strNewFile = strFileName.Left(strFileName.Find(strSymbol));

	strOldFilePath.Format(_T("%s%s.%s"),strFilePath,strNewFile,strFileExtendName);

	try
	{
		CFile::Rename(strFullFilePath,strOldFilePath);	
	}
	catch (...)
	{
		return FALSE;
	}
	return TRUE;
}

void CMes::GetFilePath(std::vector<CString>& vFilePathList, CString &strDir,BOOL & bSendOK,BOOL &bSendNG,BOOL & bSendNGC,BOOL & bSendCover)
{
	CFileFind finder;

	CString strFilePath;

	strFilePath.Format(_T("%s"),strDir);

	if (strFilePath == _T(""))
	{
		return;
	}
	else 
	{
		if (strFilePath.Right(1) != _T(""))
		{
			strFilePath += _T("\\");
		}
		strFilePath += _T("*.*");
	}

	BOOL isNotEmpty = finder.FindFile(strFilePath);//总文件夹，开始遍历 
	while(isNotEmpty)
	{
		isNotEmpty = finder.FindNextFile();//查找文件 
		CString filename = finder.GetFilePath();//获取文件的路径，可能是文件夹，可能是文件 
		if (!(finder.IsDirectory()))
		{	
			//如果是文件则加入文件列表
			CString strOldFileName;

			if (HasBeenSent(filename))	//已发送过
			{
				if (!bSendCover)	//已发送文件再发送
				{
					CString strFileName;

					CString strFileExtendName;

					CString strOldFileName;

					strFileName = filename.Right(filename.GetLength()-filename.ReverseFind('\\')-1);

					strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.Find('.')-1);

					if (strFileExtendName == _T("bmp") || strFileExtendName == _T("jpg"))
					{
						int iOKImg = 0;

						int iNGImg = 0;

						int iNGCImg = 0;

						iOKImg = strFileName.Find(_T("_OK_"));

						iNGImg = strFileName.Find(_T("_NG_"));

						iNGCImg = strFileName.Find(_T("_NGC_"));

						if (iOKImg >= 0 && bSendOK)
						{
							UNRenameFile(filename,m_strRenameSymbol,strOldFileName);

							vFilePathList.push_back(strOldFileName);//将一个文件路径加入容器
						}
						else if (iNGImg >= 0 && bSendNG)
						{
							UNRenameFile(filename,m_strRenameSymbol,strOldFileName);

							vFilePathList.push_back(strOldFileName);
						}
						else if (iNGCImg >= 0 && bSendNGC)
						{
							UNRenameFile(filename,m_strRenameSymbol,strOldFileName);

							vFilePathList.push_back(strOldFileName);
						}
						else
						{
							;
						}
					}
					else
					{
					
						if (strFileName.Find(m_strCrrentBatch) < 0)
						{
							UNRenameFile(filename,m_strRenameSymbol,strOldFileName);

							vFilePathList.push_back(strOldFileName);
						}
						
					}
				}
				else	//已发送文件不再发送
				{
				//	continue;
				}
			}
			else			//未发送过
			{
				CString strFileName;

				CString strFileExtendName;

				strFileName = filename.Right(filename.GetLength()-filename.ReverseFind('\\')-1);

				strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.Find('.')-1);

				if (strFileExtendName == _T("bmp") || strFileExtendName == _T("jpg"))
				{
					int iOKImg = 0;

					int iNGImg = 0;

					int iNGCImg = 0;

					iOKImg = strFileName.Find(_T("_OK_"));

					iNGImg = strFileName.Find(_T("_NG_"));

					iNGCImg = strFileName.Find(_T("_NGC_"));

					if (iOKImg >= 0 && bSendOK)
					{
						vFilePathList.push_back(filename);//将一个文件路径加入容器
					}
					else if (iNGImg >= 0 && bSendNG)
					{
						vFilePathList.push_back(filename);
					}
					else if (iNGCImg >= 0 && bSendNGC)
					{
						vFilePathList.push_back(filename);
					}
					else
					{
					//	continue;
					}
				}
				else
				{
					if ( strFileName.Find(m_strCrrentBatch) <  0)
					{
						vFilePathList.push_back(filename);
					}

				}
			}		
		} 
		else
		{													//递归遍历用户文件夹，跳过非用户文件夹
			if (!(finder.IsDots()||finder.IsHidden()||finder.IsSystem()||finder.IsTemporary()||finder.IsReadOnly()))
			{
				GetFilePath(vFilePathList,filename+_T("\\"),bSendOK,bSendNG,bSendNGC,bSendCover);
			}
		}
	}

}


void CMes::GetFilePath(std::vector<CString>& vFilePathList, CString &strDir,BOOL & bSendOK,BOOL &bSendNG,BOOL & bSendNGC)
{
	CFileFind finder;

	CString strFilePath;

	strFilePath.Format(_T("%s"),strDir);

	if (strFilePath == _T(""))
	{
		return;
	}
	else 
	{
		if (strFilePath.Right(1) != _T(""))
		{
			strFilePath += _T("\\");
		}
		strFilePath += _T("*.*");
	}

	BOOL isNotEmpty = finder.FindFile(strFilePath);//总文件夹，开始遍历 
	while(isNotEmpty)
	{
		isNotEmpty = finder.FindNextFile();//查找文件 
		CString filename = finder.GetFilePath();//获取文件的路径，可能是文件夹，可能是文件 
		if (!(finder.IsDirectory()))
		{	
			//如果是jpg.csv文件则加入文件列表
			
				CString strFileName;

				CString strFileExtendName;

				strFileName = filename.Right(filename.GetLength()-filename.ReverseFind('\\')-1);

				strFileExtendName = strFileName.Right(strFileName.GetLength()- strFileName.Find('.')-1);
			
				if (strFileExtendName == _T("bmp") || strFileExtendName == _T("jpg") || strFileExtendName == _T("xls"))
				{
					int iOKImg = -1;

					int iNGImg = -1;

					int iNGCImg = -1;

					//iOKImg = strFileName.Find(_T("_OK_"));

					iNGImg = strFileName.Find(_T("_NG_"));

					//iNGCImg = strFileName.Find(_T("_NGC_"));

					if (iOKImg >= 0 && bSendOK)
					{
						vFilePathList.push_back(filename);//将一个文件路径加入容器

						m_hvCurrentDisk.Append(HTuple(filename));

					}
					else if (iNGImg >= 0 && bSendNG)
					{
						vFilePathList.push_back(filename);

						m_hvCurrentDisk.Append(HTuple(filename));

					}
					else if (iNGCImg >= 0 && bSendNGC)
					{
						vFilePathList.push_back(filename);

						m_hvCurrentDisk.Append(HTuple(filename));
					}
					else 
					{
						if( ( strFileExtendName == _T("xls") ) && strFileName.Find("FTPC")>=0)
						{
							vFilePathList.push_back(filename);							
							m_hvCurrentDisk.Append(HTuple(filename));
						}

					}
					
				}				
		}
		else
		{													//递归遍历用户文件夹，跳过非用户文件夹
			if (!(finder.IsDots()||finder.IsHidden()||finder.IsSystem()||finder.IsTemporary()||finder.IsReadOnly()))
			{
				GetFilePath(vFilePathList,filename+_T("\\"),bSendOK,bSendNG,bSendNGC);
			}
		}
	}

}





void  ThreadFtpUpload(PVOID * pParam)
{
	CMes* pCMes = (CMes*)pParam;

	SYSTEMTIME currentTime;

	Sleep(2000);

	while(TRUE)
	{
		if (1 != pCMes->m_nType)
		{
			Sleep(2000);
			continue;
		}

		pCMes->m_vFilePathList.clear();

//		pCMes->GetFilePath(pCMes->m_vFilePathList,pCMes->m_strLocalRootPath,pCMes->m_bSendOK,pCMes->m_bSendNG,pCMes->m_bSendNGCrop,pCMes->m_bSendCover);

		pCMes->m_hvCurrentDisk.Clear();		//清空上一次磁盘扫描结果

		pCMes->GetFilePath(pCMes->m_vFilePathList,pCMes->m_strLocalRootPath,pCMes->m_bSendOK,pCMes->m_bSendNG,pCMes->m_bSendNGCrop);

		g_pCMesSendInfo = new CMesSendInfo[pCMes->m_iThreadNumber];

		g_pHThead = new HANDLE[pCMes->m_iThreadNumber];

		//////////////////////////////////////////////////

		CString strMessage;

		int iLenght = 0;

		int iMod = 0;

		int iSum = 0;

		int iCount = pCMes->m_vFilePathList.size();
		
		GetLocalTime(&currentTime);

		strMessage.Format(_T("%4d年%2d月%2d日%2d时%2d分%2d秒%d毫秒\t线程总数：\t%d\t文件数目：\t%d\n"),currentTime.wYear,currentTime.wMonth,currentTime.wDay,currentTime.wHour,currentTime.wMinute,
			currentTime.wSecond,currentTime.wMilliseconds,pCMes->m_iThreadNumber,iCount);

		pCMes->m_record.writeAssignmentFile(strMessage);

		iLenght = iCount /pCMes->m_iThreadNumber;

		iMod = iCount % pCMes->m_iThreadNumber;

		if (0 == iCount)
		{
			Sleep(pCMes->m_intervalMinute * 60 * 1000);
			continue;
		}

		for (int i = 0; i < pCMes->m_iThreadNumber ;i++)
		{
			g_pCMesSendInfo[i].pCMes = pCMes;

			g_pCMesSendInfo[i].id = i;

			g_pCMesSendInfo[i].vFilePathList = pCMes->m_vFilePathList;

			if (iMod > 0)
			{
				g_pCMesSendInfo[i].iLenght = iLenght + 1;
			}
			else
			{
				g_pCMesSendInfo[i].iLenght = iLenght ;
			}

			iMod--;

			iSum += g_pCMesSendInfo[i].iLenght;

			g_pCMesSendInfo[i].iSum = iSum;

			g_pHThead[i] = ::CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)ThreadProcDynamic,&g_pCMesSendInfo[i],NULL,NULL);
		}

		WaitForMultipleObjects(pCMes->m_iThreadNumber, g_pHThead, TRUE,INFINITE);

		if (NULL != g_pCMesSendInfo)
		{
			delete[] g_pCMesSendInfo;

			g_pCMesSendInfo = NULL;
		}
		if (NULL != g_pHThead)
		{
			delete[] g_pHThead;

			g_pHThead = NULL;
		}
		///////////////////////////////////////////////////

		Sleep(pCMes->m_intervalMinute * 60 * 1000);
	}
}

void  ThreadFtpUpload_1(PVOID * pParam)
{
	CMes* pCMes = (CMes*)pParam;

	SYSTEMTIME currentTime;

	Sleep(2000);

	

	while(!pCMes->m_bExit)
	{
		if (1 != pCMes->m_nType || 0 == pCMes->m_nType)
		{
			Sleep(2000);
			continue;
		}

		pCMes->m_vFilePathList.clear();

		//		pCMes->GetFilePath(pCMes->m_vFilePathList,pCMes->m_strLocalRootPath,pCMes->m_bSendOK,pCMes->m_bSendNG,pCMes->m_bSendNGCrop,pCMes->m_bSendCover);

		pCMes->m_hvCurrentDisk.Clear();		//清空上一次磁盘扫描结果

		int  iCount = 0;

		try
		{

			pCMes->GetFilePath(pCMes->m_vFilePathList,pCMes->m_strLocalRootPath,pCMes->m_bSendOK,pCMes->m_bSendNG,pCMes->m_bSendNGCrop);
			pCMes->GetFilePath(pCMes->m_vFilePathList, pCMes->m_strLocalRootPathP, pCMes->m_bSendOK, pCMes->m_bSendNG, pCMes->m_bSendNGCrop);

			HTuple hvUploadFile;	//需要上传的文件集合

			HTuple hvDeletFile;		//已经删除的文件集合

			TupleDifference(pCMes->m_hvUploaded,pCMes->m_hvCurrentDisk,&hvDeletFile);	//找出已经删除的文件

			TupleDifference(pCMes->m_hvUploaded,hvDeletFile,&pCMes->m_hvUploaded);	//去除已经删除的文件

			TupleDifference(pCMes->m_hvCurrentDisk,pCMes->m_hvUploaded,&pCMes->m_hvCurrentDisk);	//过滤已经上传的文件

			iCount = pCMes->m_hvCurrentDisk.Length();

			pCMes->m_vFilePathList.clear();	//清空上次上传文件列表

			for (int i = 0 ; i < iCount ; i++)
			{
				pCMes->m_vFilePathList.push_back(pCMes->m_hvCurrentDisk[i].S().Text());
			}

		}
		catch (HException& e)
		{

			CString strMsg,strFunc;

			strMsg.Format("扫盘处理tuple异常\t%s",e.ErrorMessage().Text());
			
			pCMes->m_pSoapMesLog->AssignmentLog(strMsg);

			continue;
		}

		//线程数固定为1
		pCMes->m_iThreadNumber = 1;

		//////////////////////////////////////////////////

		CString strMessage;

		int iLenght = 0;

		int iMod = 0;

		int iSum = 0;

		int iThreadCreate = 0;

		iLenght = iCount /pCMes->m_iThreadNumber;

		iMod = iCount % pCMes->m_iThreadNumber;

	//	int iCount = pCMes->m_vFilePathList.size();

		if ( 0 == iLenght && iLenght < pCMes->m_iThreadNumber )
		{
			iThreadCreate = iMod;
		}
		else
		{
			iThreadCreate = pCMes->m_iThreadNumber;
		}

		GetLocalTime(&currentTime);

		//strMessage.Format(_T("线程总数：\t%d\t文件数目：\t%d"),iThreadCreate,iCount);

		//pCMes->m_pSoapMesLog->AssignmentLog(strMessage);

		if (0 == iCount)
		{
			Sleep(pCMes->m_intervalMinute * 60 * 1000);
			continue;
		}

		g_pCMesSendInfo = new CMesSendInfo[iThreadCreate];

		g_pHThead = new HANDLE[iThreadCreate];

		memset(g_pHThead,0,sizeof(HANDLE)* iThreadCreate);

		for (int i = 0; i < iThreadCreate ;i++)
		{
			g_pCMesSendInfo[i].pCMes = pCMes;

			g_pCMesSendInfo[i].id = i;

			g_pCMesSendInfo[i].vFilePathList = pCMes->m_vFilePathList;

			if (iMod > 0)
			{
				g_pCMesSendInfo[i].iLenght = iLenght + 1;
			}
			else
			{
				g_pCMesSendInfo[i].iLenght = iLenght ;
			}

			iMod--;

			iSum += g_pCMesSendInfo[i].iLenght;

			g_pCMesSendInfo[i].iSum = iSum;

			g_pHThead[i] = ::CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)ThreadProcDynamic_1,&g_pCMesSendInfo[i],NULL,NULL);

		}

		WaitForMultipleObjects(iThreadCreate, g_pHThead, TRUE,INFINITE);

		for(int i = 0;i < iThreadCreate ; i++)
		{
			CloseHandle(g_pHThead[i]);	
		}

		if (NULL != g_pCMesSendInfo)
		{
			delete[] g_pCMesSendInfo;

			g_pCMesSendInfo = NULL;
		}
		if (NULL != g_pHThead)
		{
			delete[] g_pHThead;

			g_pHThead = NULL;
		}
		///////////////////////////////////////////////////

		Sleep(pCMes->m_intervalMinute * 60 * 1000);
	}

	
}



UINT ThreadProcDynamic(LPVOID lpVoid)
{
	CMesSendInfo *lpSendInfo = (CMesSendInfo*)lpVoid;

	std::vector<CString>::iterator iterStart ,iterEnd;

	iterStart	= lpSendInfo->vFilePathList.begin() + lpSendInfo->iSum - lpSendInfo->iLenght;

	iterEnd = iterStart + lpSendInfo->iLenght;

	CString strMessage;

	SYSTEMTIME currentTime;

	GetLocalTime(&currentTime);

	int iStart,iLenght;

	iStart = iterStart - lpSendInfo->vFilePathList.begin();

	iLenght = iterEnd - iterStart;

	strMessage.Format(_T("线程号：\t%d\t起始：\t%d\t长度：\t%d\n"),lpSendInfo->id,iStart,iLenght);

	lpSendInfo->pCMes->m_record.writeAssignmentFile(strMessage);

	int i = lpSendInfo->id;

	for (std::vector<CString>::iterator iter = iterStart;iter != iterEnd ;iter++)
	{
		lpSendInfo->pCMes->FtpUploadFile(*iter);
	}

	return	0;
}

UINT ThreadProcDynamic_1(LPVOID lpVoid)
{
	CMesSendInfo *lpSendInfo = (CMesSendInfo*)lpVoid;

	std::vector<CString>::iterator iterStart ,iterEnd;

	iterStart	= lpSendInfo->vFilePathList.begin() + lpSendInfo->iSum - lpSendInfo->iLenght;

	iterEnd = iterStart + lpSendInfo->iLenght;

	CString strMessage;

	SYSTEMTIME currentTime;

	GetLocalTime(&currentTime);

	int iStart,iLenght;

	double dCPUUserRate = 0;                        //CPU使用的百分比 

	iStart = iterStart - lpSendInfo->vFilePathList.begin();

	iLenght = iterEnd - iterStart;

	//strMessage.Format(_T("线程号：\t%d\t起始：\t%d\t长度：\t%d"),lpSendInfo->id,iStart,iLenght);

	//lpSendInfo->pCMes->m_pSoapMesLog->AssignmentLog(strMessage);

	int i = lpSendInfo->id;

	for (std::vector<CString>::iterator iter = iterStart;iter != iterEnd ;iter++)
	{
		if (0 == lpSendInfo->pCMes->m_nType)
		{
			continue;
		}

		//if (lpSendInfo->pCMes->m_bSendCover)			//是否过滤已上传文件
		//{
		//	if (!lpSendInfo->pCMes->IsUpload(*iter))		//是否上传检测
		//	{
		//		continue;
		//	}
		//}
		
		while(!lpSendInfo->pCMes->m_bExit)
		{
			lpSendInfo->pCMes->picProcessInfoCollect.GetCPUUserRate(dCPUUserRate); 

			strMessage.Format(_T("CPU Rate：\t%0.3f\n"),dCPUUserRate);

		//	lpSendInfo->pCMes->m_record.writeMSG(strMessage);

			if (dCPUUserRate > 30)   //CPU 消耗大于25%  暂停上传ftp文件
			{
				Sleep(1000 * lpSendInfo->pCMes->m_intervalMinute);
			}
			else
			{
				break;
			}
		}

		if (lpSendInfo->pCMes->m_bExit)
		{
			break;
		}
		lpSendInfo->pCMes->FtpUploadFile(*iter);
	}

	//lpSendInfo->pCMes->WriteUploadTuple();

	return	0;
}


UINT ThreadOnInfo(LPVOID lpVoid)
{
	CMes* pCMes = (CMes*)lpVoid;
	int nStauts(0);

	while(!pCMes->m_bExit)
	{
		if (FALSE)
		{
			pCMes->m_iConnectStauts = pCMes->ReportOnlieInfo();
		}
		else
		{
			int iRes(-100);
			int nCode;
			neb::CJsonObject CJsonRcv;
			iRes = pCMes->Soap_Heatbeat(true,CJsonRcv);
			CJsonRcv.Get("code",nCode);
			if (SOAP_OK == iRes && 1 == nCode)
			{
				pCMes->m_iConnectStauts = 200;
			}
			else
			{
				pCMes->m_iConnectStauts = 0;
			}

		}
		Sleep(1000 * pCMes->m_nHeartBeatTime);
	}

	return	0;
}

BOOL CMes::StartThread(void)
{
	m_ThreadFtpUpload = AfxBeginThread((AFX_THREADPROC)ThreadFtpUpload_1,this);
	//AfxBeginThread((AFX_THREADPROC)ThreadOnInfo,this);
	return TRUE;
}


BOOL CMes::Batch(CString &strBatch)
{
	m_strCrrentBatch.Format(_T("%s"),strBatch);
	return TRUE;
}


int CMes::UpdateRecipeInfo(PRECIPEINFO pInfo)
{
	/*m_strRecipeCode = pInfo->cstrRecipeCode;
	m_strRecipeVison = pInfo->cstrVison;
	m_strProductCode = pInfo->cstrProductCode;*/
	return 1;
}


int CMes::InitRecipe(CString const & cstrPath)
{
	if (cstrPath.Find(_T("\\SCIDetect")) >= 0)			//瑕疵
	{
		CString cstrRecipeParamIniPath;

		CString cstrRecipeParamPath;

		cstrRecipeParamIniPath.Format(_T("%s\\Detect.ini"),cstrPath);	//版本信息文件夹

		cstrRecipeParamPath.Format(_T("%s\\0\\缺陷检测"),cstrPath);	//缺陷参数文件夹

//		m_strRecipeCode = GetPrivateProfileCString("RecipeInfo","RecipeCode","",cstrRecipeParamIniPath);

//		m_strProductCode = GetPrivateProfileCString("RecipeInfo","ProdctCode","",cstrRecipeParamIniPath);

//		m_strRecipeVison = GetPrivateProfileCString("RecipeInfo","RecipeVison","",cstrRecipeParamIniPath);

		return GetDefectRecipeParam(cstrRecipeParamPath);
	}
	else if (cstrPath.Find(_T("ModelInfo")) >= 0)	//尺寸
	{

		return GetSizeRecipeParam(cstrPath);
	}
	else
	{
		return 0;
	}
	
}


int CMes::GetDefectRecipeParam(CString const & cstrPath)
{
	try
	{	CString cstrTimestamp;

		SYSTEMTIME iLocalTime;

		HTuple AllFiles ,hvParamFiles;

		ListFiles(HTuple(cstrPath), "files", &AllFiles);

		TupleRegexpSelect(AllFiles, (HTuple("\\.(tup)$").Append("ignore_case")), &hvParamFiles);

		HTuple Length, Index, Substring;

		TupleStrlen(hvParamFiles, &Length);

		TupleStrrchr(hvParamFiles, "\\", &Index);

		TupleSubstr(hvParamFiles, Index + 1, Length - 5, &Substring); // 获取文件名

		int iCount = Substring.Length() + 3;

		m_pCJsonRecipeParam = new neb::CJsonObject[Substring.Length()+3]; //创建参数json对象数组 增加黑点、凹坑、白点个数

		GetLocalTime(&iLocalTime);

		cstrTimestamp.Format(_T("%4d-%2d-%2dT%2d:%2d:%2d.%3d+08:00"),
			iLocalTime.wYear,iLocalTime.wMonth,iLocalTime.wDay,iLocalTime.wHour,iLocalTime.wMinute,iLocalTime.wSecond,iLocalTime.wMilliseconds);

		m_cJsonRecipes.AddEmptySubArray("Parameters");

		for (int i = Substring.Length()-1; i>=0; i--)		//添加需要上传参数json
		{
			HTuple hvTuple;

			CString cstrMinValue,cstrMaxValue,cstrTupleName;

			cstrTupleName.Format("%s",Substring[i].S().Text());

			int nIndex = -1;

			int iIndex = 0;

			int nLenght = sizeof(g_cstrRecipeParamName)/sizeof(g_cstrRecipeParamName[0]);

			for(; iIndex < nLenght;iIndex++)
			{
				if (cstrTupleName == g_cstrRecipeParamName[iIndex])
				{
					nIndex = iIndex;
				}
			}

			if (nIndex < 0 || nIndex >= nLenght)
			{
				continue;
			}
			else
			{
				ReadTuple(hvParamFiles[i], &hvTuple);

				switch (nIndex)
				{
				case 0:		//黑点
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}


						//增加黑点个数
						{
							CString cstrValue;

							if (hvTuple[13] == HTuple(hvTuple[13]).TupleInt())
							{
								cstrValue.Format("%d", HTuple(hvTuple[13]).TupleInt().I());
							}
							else if (1 == HTuple(hvTuple[13]).TupleIsReal())
							{	
								cstrValue.Format("%.4f", hvTuple[13].D());
							}

							m_pCJsonRecipeParam[iCount - 3].Add("ParameterCode",g_cstrRecipeParamCode[nLenght - 3].GetString());

							m_pCJsonRecipeParam[iCount - 3].Add("ParameterValue",cstrValue.GetString());

					//		m_pCJsonRecipeParam[iCount - 3].Add("ParameterMinValue","");

					//		m_pCJsonRecipeParam[iCount - 3].Add("ParameterMaxValue","");

							m_pCJsonRecipeParam[iCount - 3].Add("Timestamp",cstrTimestamp.GetString());

						}

						break;
					}
				case 1:		//黑线
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}

						break;
					}
				case 2:		//凹痕
					{
						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[10].D());		
						}

						if (hvTuple[13] == HTuple(hvTuple[13]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[13]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[13]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[13].D());
						}

						//增加凹坑个数
						{
							CString cstrValue;

							if (hvTuple[16] == HTuple(hvTuple[16]).TupleInt())
							{
								cstrValue.Format("%d", HTuple(hvTuple[16]).TupleInt().I());
							}
							else if (1 == HTuple(hvTuple[16]).TupleIsReal())
							{	
								cstrValue.Format("%.4f", hvTuple[16].D());
							}

							m_pCJsonRecipeParam[iCount - 2].Add("ParameterCode",g_cstrRecipeParamCode[nLenght - 2].GetString());

							m_pCJsonRecipeParam[iCount - 2].Add("ParameterValue",cstrValue.GetString());

							m_pCJsonRecipeParam[iCount - 2].Add("Timestamp",cstrTimestamp.GetString());

						}

						break;
					}
				case 3:		//白点
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}


						//增加白点个数
						{
							CString cstrValue;

							if (hvTuple[13] == HTuple(hvTuple[13]).TupleInt())
							{
								cstrValue.Format("%d", HTuple(hvTuple[13]).TupleInt().I());
							}
							else if (1 == HTuple(hvTuple[13]).TupleIsReal())
							{	
								cstrValue.Format("%.4f", hvTuple[13].D());
							}

							m_pCJsonRecipeParam[iCount - 1].Add("ParameterCode",g_cstrRecipeParamCode[nLenght - 1].GetString());

							m_pCJsonRecipeParam[iCount - 1].Add("ParameterValue",cstrValue.GetString());

							m_pCJsonRecipeParam[iCount - 1].Add("Timestamp",cstrTimestamp.GetString());

						}

						break;
					}
				case 4:			//白线
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}

						break;
					}
				case 5:	//边界漏箔
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}

						break;
					}
				case 6:		//边线漏箔
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}

						break;
					}
				case 7:		// 漏箔
					{
						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[10].D());		
						}

						if (hvTuple[13] == HTuple(hvTuple[13]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[13]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[13]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[13].D());
						}

						break;
					}
				case 8:	//交界处漏箔
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}

						break;
					}
				case 9:		//气泡
					{
						if (hvTuple[7] == HTuple(hvTuple[7]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[7]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[7]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[7].D());		
						}

						if (hvTuple[10] == HTuple(hvTuple[10]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[10]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[10]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[10].D());
						}
						break;
					}
				case 10:	//未涂或未辊压
					{
						if (hvTuple[22] == HTuple(hvTuple[22]).TupleInt())
						{
							cstrMinValue.Format("%d", HTuple(hvTuple[22]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[22]).TupleIsReal())
						{	
							cstrMinValue.Format("%.4f", hvTuple[22].D());		
						}

						if (hvTuple[25] == HTuple(hvTuple[25]).TupleInt())
						{
							cstrMaxValue.Format("%d", HTuple(hvTuple[25]).TupleInt().I());
						}
						else if (1 == HTuple(hvTuple[25]).TupleIsReal())
						{	
							cstrMaxValue.Format("%.4f", hvTuple[25].D());
						}
						break;
					}

				default:
					{
						cstrMinValue.Format("");

						cstrMaxValue.Format("");
					}
					break;
				}
				if ("" == cstrMinValue || "" == cstrMaxValue)
				{
					continue;
				}
				m_pCJsonRecipeParam[i].Add("ParameterCode",g_cstrRecipeParamCode[nIndex].GetString());

				m_pCJsonRecipeParam[i].Add("ParameterMinValue",cstrMinValue.GetString());

				m_pCJsonRecipeParam[i].Add("ParameterMaxValue",cstrMaxValue.GetString());

				m_pCJsonRecipeParam[i].Add("Timestamp",cstrTimestamp.GetString());

				m_cJsonRecipes["Parameters"].Add(m_pCJsonRecipeParam[i]);
			}
		}

		m_cJsonRecipes["Parameters"].Add(m_pCJsonRecipeParam[iCount - 3]);

		m_cJsonRecipes["Parameters"].Add(m_pCJsonRecipeParam[iCount - 2]);

		m_cJsonRecipes["Parameters"].Add(m_pCJsonRecipeParam[iCount - 1]);

		m_cJsonRecipes.Add("RecipeCode",m_strRecipeCode.GetString());

		m_cJsonRecipes.Add("ProductCode",m_strProductCode.GetString());

		m_cJsonRecipes.Add("Version",m_strRecipeVison.GetString());

		m_cJsonRecipes.Add("LineCode",m_strLineCode.GetString());

		m_cJsonRecipes.Add("SectionCode",m_strSectionCode.GetString());

		m_cJsonRecipes.Add("EquipmentCode",m_strEquipmentCode.GetString());

		m_cJsonRecipes.Add("Timestamp",cstrTimestamp.GetString());

		std::string strRecipe;

		strRecipe = "[" + m_cJsonRecipes.ToString() + "]";

	}catch(HException e)
	{
		AfxMessageBox(e.ErrorMessage().Text());

		if (m_pCJsonRecipeParam)
		{
			delete[] m_pCJsonRecipeParam;

			m_pCJsonRecipeParam = NULL;
		}

		return 0;
	}

	if (m_pCJsonRecipeParam)
	{
		delete[] m_pCJsonRecipeParam;

		m_pCJsonRecipeParam = NULL;
	}

	return 1;
}


int CMes::GetSizeRecipeParam(CString const & cstrPath)
{
	double iMaxValue = 0;
	double iMinValue = 0;

	CString cstrMaxValue;
	CString cstrMinValue;

	CString cstrTimestamp;

	SYSTEMTIME iLocalTime;

	GetLocalTime(&iLocalTime);

	cstrTimestamp.Format(_T("%4d-%2d-%2dT%2d:%2d:%2d.%3d+08:00"),
		iLocalTime.wYear,iLocalTime.wMonth,iLocalTime.wDay,iLocalTime.wHour,iLocalTime.wMinute,iLocalTime.wSecond,iLocalTime.wMilliseconds);

	m_cJsonRecipes.AddEmptySubArray("Parameters");

	m_pCJsonRecipeParam = new neb::CJsonObject[sizeof(g_cstrSizeParamCode)/sizeof(g_cstrSizeParamCode[0])];

	try
	{
		for (int i = 0 ; i < sizeof(g_cstrSizeParamCode)/sizeof(g_cstrSizeParamCode[0]);i++)
		{
			switch (i)
			{
			case 0:		//极片长									涂布高
				{
					iMaxValue = GetPrivateProfileDouble("SizeUpDown","COAT_HEIGHTMAX",25.2,cstrPath);
					iMinValue = GetPrivateProfileDouble("SizeUpDown","COAT_HEIGHTMIN",24.8,cstrPath);
					break;
				}
			case 1:		//极片宽									涂布宽
				{
					iMaxValue = GetPrivateProfileDouble("SizeUpDown","COAT_WIDTHMAX",110,cstrPath);
					iMinValue = GetPrivateProfileDouble("SizeUpDown","COAT_WIDTHMIN",90,cstrPath);
					break;
				}
			case 2:		//极耳长									极耳宽
				{
					iMaxValue = GetPrivateProfileDouble("SizeUpDown","FOIL_WIDTHMAX",110,cstrPath);
					iMinValue = GetPrivateProfileDouble("SizeUpDown","FOIL_WIDTHMIN",90,cstrPath);
					break;
				}
			case 3:		//极耳高									极耳高
				{
					iMaxValue = GetPrivateProfileDouble("SizeUpDown","FOIL_HEIGHTMAX",25.2,cstrPath);
					iMinValue = GetPrivateProfileDouble("SizeUpDown","FOIL_HEIGHTMIN",24.8,cstrPath);
					break;
				}
			case 4:		//极耳料高									定位边不齐
				{
					iMaxValue = GetPrivateProfileDouble("SizeUpDown","MISMATCHMAX",3,cstrPath);
					iMinValue = GetPrivateProfileDouble("SizeUpDown","MISMATCHMIN",-1,cstrPath);
					break;
				}
			case 5:		//极耳肩宽									极耳肩宽
				{
					iMaxValue = GetPrivateProfileDouble("SizeUpDown","DISTANCEMAX",1.55,cstrPath);
					iMinValue = GetPrivateProfileDouble("SizeUpDown","DISTANCEMIN",-1.55,cstrPath);
					break;
				}
				
			}

			cstrMaxValue.Format(_T("%0.2f"),iMaxValue);

			cstrMinValue.Format(_T("%0.2f"),iMinValue);

			m_pCJsonRecipeParam[i].Add("ParameterCode",g_cstrRecipeParamCode[i+11].GetString());

			m_pCJsonRecipeParam[i].Add("ParameterMinValue",cstrMinValue.GetString());

			m_pCJsonRecipeParam[i].Add("ParameterMaxValue",cstrMaxValue.GetString());

			m_pCJsonRecipeParam[i].Add("Timestamp",cstrTimestamp.GetString());

			m_cJsonRecipes["Parameters"].Add(m_pCJsonRecipeParam[i]);
		}
		
		m_cJsonRecipes.Add("RecipeCode",m_strRecipeCode.GetString());

		m_cJsonRecipes.Add("ProductCode",m_strProductCode.GetString());

		m_cJsonRecipes.Add("Version",m_strRecipeVison.GetString());

		m_cJsonRecipes.Add("LineCode",m_strLineCode.GetString());

		m_cJsonRecipes.Add("SectionCode",m_strSectionCode.GetString());

		m_cJsonRecipes.Add("EquipmentCode",m_strEquipmentCode.GetString());

		m_cJsonRecipes.Add("Timestamp",cstrTimestamp.GetString());

		std::string strRecipe;

		strRecipe = "[" + m_cJsonRecipes.ToString() + "]";
	}
	catch (...)
	{
		if (m_pCJsonRecipeParam)
		{
			delete[] m_pCJsonRecipeParam;

			m_pCJsonRecipeParam = NULL;
		}

		return 0;
	}

	if (m_pCJsonRecipeParam)
	{
		delete[] m_pCJsonRecipeParam;

		m_pCJsonRecipeParam = NULL;
	}
	return 1;
}

int CMes::ReportDefectCountInfo( s_Count& countInfo)
{

	neb::CJsonObject cJsonSend;
	
	neb::CJsonObject cJsonCount[3][3];

	neb::CJsonObject cJsonErrorType[3][11];

	CString cstrTimeStamp;

	SYSTEMTIME iLocalTime;

	GetLocalTime(&iLocalTime);

	cstrTimeStamp.Format(_T("%04d-%02d-%02dT%02d:%02d:%02d.%03d+08:00"),
		iLocalTime.wYear,iLocalTime.wMonth,iLocalTime.wDay,iLocalTime.wHour,iLocalTime.wMinute,iLocalTime.wSecond,iLocalTime.wMilliseconds);

	cJsonSend.AddEmptySubArray("Parameters");

	for (int i = 0 ; i < 3 ; i++)
	{
		int iIndex = 0;

		int iErrorType = sizeof(g_cstrDetectParamCode[0])/sizeof(g_cstrDetectParamCode[0][0]);

		int iValue = 0;

		for (int j =0 ; j < iErrorType; j++)
		{
			if (_T("") == g_cstrDetectParamCode[i][j])
			{
				continue;
			}

			iValue = countInfo.veCountBatch[i].at(0).nClassError[j];

			CString cstrErrorName;

			cstrErrorName.Format(_T("%s%d"),g_cstrErrorName[j],i);

	//		cJsonErrorType[i][iIndex].Add("ParamName",cstrErrorName.GetString());
			
			cJsonErrorType[i][iIndex].Add("ParameterCode",g_cstrDetectParamCode[i][j].GetString());

			cJsonErrorType[i][iIndex].Add("ParameterValue",iValue);

			cJsonErrorType[i][iIndex].Add("Timestamp",cstrTimeStamp.GetString());

			cJsonSend["Parameters"].Add(cJsonErrorType[i][iIndex]);

			iIndex++;
		}

	}
	for (int k = 0 ; k < 3 ; k++)
	{
		CString cstrYield;

		cJsonCount[k][0].Add("ParameterCode",g_cstrDetectCountCode[k][0].GetString());

		cJsonCount[k][0].Add("ParameterValue",countInfo.nTotalBatch[k]);

		cJsonCount[k][0].Add("Timestamp",cstrTimeStamp.GetString());

		cJsonCount[k][1].Add("ParameterCode",g_cstrDetectCountCode[k][1].GetString());

		cJsonCount[k][1].Add("ParameterValue",countInfo.veCountBatch[k].at(0).nError);

		cJsonCount[k][1].Add("Timestamp",cstrTimeStamp.GetString());

		cstrYield.Format("%0.2f",countInfo.nTotalBatch[k] > 0 ? (1 -  (double)countInfo.veCountBatch[k].at(0).nError / (double)countInfo.nTotalBatch[k]) * 100 : 100);

		cJsonCount[k][2].Add("ParameterCode",g_cstrDetectCountCode[k][2].GetString());

		cJsonCount[k][2].Add("ParameterValue",cstrYield.GetString());

		cJsonCount[k][2].Add("Timestamp",cstrTimeStamp.GetString());

		cJsonSend["Parameters"].Add(cJsonCount[k][0]);

		cJsonSend["Parameters"].Add(cJsonCount[k][1]);

		cJsonSend["Parameters"].Add(cJsonCount[k][2]);
	}
	
	cJsonSend.Add("ProductBarcode",m_strCrrentBatch.GetString());

	cJsonSend.Add("LineCode",m_strLineCode.GetString()); 

	cJsonSend.Add("SectionCode",m_strSectionCode.GetString());

	cJsonSend.Add("EquipmentCode",m_strEquipmentCode.GetString());

	cJsonSend.Add("Timestamp",cstrTimeStamp.GetString());
	
	std::string strSendMessage,strSendUTF8,strRespon;

	CString cstrMessage;

	int iRet;

	strSendMessage = "[" + cJsonSend.ToString() + "]";

	strSendUTF8 = AsciiToUtf8(strSendMessage);

	iRet = MESReportProcessingParameter((CString)strSendUTF8.c_str(),strRespon);

	if (200 != iRet)
	{

	//	cstrMessage.Format(_T("MESReportProcessingParameter;返回码：%d\t返回信息：%s\n发送信息：%s"),iRet,strRespon.c_str(),strSendMessage.c_str());

	//	Log(cstrMessage);

	//	m_record.writeHttpFile(cstrMessage);
		m_cJsonResend.Clear();
		m_cJsonResend = cJsonSend;

		AfxBeginThread((AFX_THREADPROC)ReSendReportProcessingParam,this);

	}

	if (200 == iRet)
	{
		cstrMessage.Format(_T("MESReportProcessingParameter;返回码：%d\t\n发送信息：%s"),iRet,strSendMessage.c_str());

		m_record.writeHttpFile(cstrMessage);
	}

	return 1;
}

int CMes::Soap_DefectCountInfo( s_Count& countInfo)
{
 	int iRet(-10),nCode(-10);
	ParamEquipmentProductProcess paramEquipmentProductProcess;

	paramEquipmentProductProcess.cstrSFC = m_strCrrentBatch;

	time_t timeStamp;

	time(&timeStamp);

	for (int i = 0 ; i < 3 ; i++)
	{
		int iErrorType = sizeof(g_cstrDetectParamCode[0])/sizeof(g_cstrDetectParamCode[0][0]);
		int iValue = 0;
		for (int j =0 ; j < iErrorType; j++)
		{
			if (_T("") == g_cstrDetectParamCode[i][j])
			{
				continue;
			}
			iValue = countInfo.veCountBatch[i].at(0).nClassError[j];
			CString cstrErrorName;
			cstrErrorName.Format(_T("%s%d"),g_cstrErrorName[j],i);   //Ng类型名称
			ParamProductProcessBase paramBase;
			paramBase.cstrParamCode = g_cstrDetectParamCode[i][j];
			paramBase.cstrParamValue.Format("%d",iValue);
			paramBase.timeStamp = timeStamp;

			paramEquipmentProductProcess.vecParamList.push_back(paramBase);
		}

	}
	for (int k = 0 ; k < 3 ; k++)
	{
		CString cstrYield;
		ParamProductProcessBase paramBase;

		paramBase.cstrParamCode.Format("%s",g_cstrDetectCountCode[k][0]);
		paramBase.cstrParamValue.Format("%d",countInfo.nTotalBatch[k]);
		paramBase.timeStamp = timeStamp;
		paramEquipmentProductProcess.vecParamList.push_back(paramBase);

		paramBase.cstrParamCode.Format("%s",g_cstrDetectCountCode[k][1]);
		paramBase.cstrParamValue.Format("%d",countInfo.veCountBatch[k].at(0).nError);
		paramBase.timeStamp = timeStamp;
		paramEquipmentProductProcess.vecParamList.push_back(paramBase);

		cstrYield.Format("%0.2f",countInfo.nTotalBatch[k] > 0 ? (1 -  (double)countInfo.veCountBatch[k].at(0).nError / (double)countInfo.nTotalBatch[k]) * 100 : 100);

		paramBase.cstrParamCode.Format("%s",g_cstrDetectCountCode[k][2]);
		paramBase.cstrParamValue.Format("%s",cstrYield);
		paramBase.timeStamp = timeStamp;
		paramEquipmentProductProcess.vecParamList.push_back(paramBase);
		
	}

	iRet = Soap_equipmentProductProcessParam(paramEquipmentProductProcess,neb::CJsonObject(),neb::CJsonObject());
	
	return iRet;
}

int CMes::Soap_SizeCountInfo(s_Count_Size  & CountInfo)
{
	int iRet(-10),nCode(-10);
	ParamEquipmentProductProcess paramEquipmentProductProcess;
	paramEquipmentProductProcess.cstrSFC = m_strCrrentBatch;
	time_t timeStamp;
	time(&timeStamp);
	ParamProductProcessBase paramBase;

	int iIndex = 0;
	int iErrorType = sizeof(g_cstrSizeParamCode)/sizeof(g_cstrSizeParamCode[0]);
	int iValue = 0;
	for (int j =0 ; j < iErrorType; j++)
	{
		if (_T("") == g_cstrSizeParamCode[j])
		{
			continue;
		}
		iValue = CountInfo.vecErrorBatchCount[j].nCount;
		CString cstrErrorName;
		cstrErrorName.Format(_T("%s"),CountInfo.strArrayErrorName.GetAt(j));

		//	cJsonErrorType[iIndex].Add("ParamName",cstrErrorName.GetString());
		paramBase.cstrParamCode.Format("%s",g_cstrSizeParamCode[j]);
		paramBase.cstrParamValue.Format("%d",iValue);
		paramBase.timeStamp = timeStamp;
		paramEquipmentProductProcess.vecParamList.push_back(paramBase);

	}
	CString cstrYield;
	paramBase.cstrParamCode.Format("%s",g_cstrsSizeCountCode[0]);
	paramBase.cstrParamValue.Format("%d",CountInfo.nBatchTotal);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);

	paramBase.cstrParamCode.Format("%s",g_cstrsSizeCountCode[1]);
	paramBase.cstrParamValue.Format("%d",CountInfo.nErrorBatchTotal);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);

	cstrYield.Format("%0.2f",CountInfo.nBatchTotal > 0 ? (1 - (double)CountInfo.nErrorBatchTotal / (double)CountInfo.nBatchTotal) * 100 : 100);

	paramBase.cstrParamCode.Format("%s",g_cstrsSizeCountCode[2]);
	paramBase.cstrParamValue.Format("%s",cstrYield);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);

	iRet = Soap_equipmentProductProcessParam(paramEquipmentProductProcess,neb::CJsonObject(),neb::CJsonObject());
	return iRet;
}
int CMes::Soap_CountInfo( Total_Count  & CountInfo)
{
	int iRet(-10),nCode(-10);
	ParamEquipmentProductProcess paramEquipmentProductProcess;
	paramEquipmentProductProcess.cstrSFC = m_strCrrentBatch;
	time_t timeStamp;
	time(&timeStamp);
	ParamProductProcessBase paramBase;
	

	//  总数量 DAMQ0011  良品数量 DAMQ0012  外观不良数量 DAMQ0013  尺寸不良数量 DAMQ0014 良品率 DAMQ0015



	CString cstrYield;
	//  总数量 DAMQ0011
	paramBase.cstrParamCode.Format("%s", "DAMQ0011");
	paramBase.cstrParamValue.Format("%d",CountInfo.totalCount);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);

	//  良品数量 DAMQ0012
	paramBase.cstrParamCode.Format("%s", "DAMQ0012");
	paramBase.cstrParamValue.Format("%d",CountInfo.totalOKCount);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);

	//外观不良数量 DAMQ0013
	paramBase.cstrParamCode.Format("%s", "DAMQ0013");
	paramBase.cstrParamValue.Format("%d",CountInfo.detectNGCount);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);

	//尺寸不良数量 DAMQ0014
	paramBase.cstrParamCode.Format("%s", "DAMQ0014");
	paramBase.cstrParamValue.Format("%d",CountInfo.sizeNGCount);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);
	
	//良品率 DAMQ0015
	cstrYield.Format("%0.2f",CountInfo.totalCount > 0 ? ((double)CountInfo.totalOKCount / (double)CountInfo.totalCount) * 100 : 0);
	paramBase.cstrParamCode.Format("%s", "DAMQ0015");
	paramBase.cstrParamValue.Format("%s",cstrYield);
	paramBase.timeStamp = timeStamp;
	paramEquipmentProductProcess.vecParamList.push_back(paramBase);
	
	iRet = Soap_equipmentProductProcessParam(paramEquipmentProductProcess,neb::CJsonObject(),neb::CJsonObject());

	return iRet;
}
int CMes::ReportSizeCountInfo( s_Count_Size  & CountInfo)
{
	neb::CJsonObject cJsonSend;

	neb::CJsonObject cJsonCount[3];

	neb::CJsonObject cJsonErrorType[6];

	CString cstrTimeStamp;

	SYSTEMTIME iLocalTime;

	GetLocalTime(&iLocalTime);

	cstrTimeStamp.Format(_T("%04d-%02d-%02dT%02d:%02d:%02d.%03d+08:00"),
		iLocalTime.wYear,iLocalTime.wMonth,iLocalTime.wDay,iLocalTime.wHour,iLocalTime.wMinute,iLocalTime.wSecond,iLocalTime.wMilliseconds);

	cJsonSend.AddEmptySubArray("Parameters");

	int iIndex = 0;

	int iErrorType = sizeof(g_cstrSizeParamCode)/sizeof(g_cstrSizeParamCode[0]);

	int iValue = 0;

	for (int j =0 ; j < iErrorType; j++)
	{
		if (_T("") == g_cstrSizeParamCode[j])
		{
			continue;
		}

		iValue = CountInfo.vecErrorBatchCount[j].nCount;

		CString cstrErrorName;

		cstrErrorName.Format(_T("%s"),CountInfo.strArrayErrorName.GetAt(j));

	//	cJsonErrorType[iIndex].Add("ParamName",cstrErrorName.GetString());

		cJsonErrorType[iIndex].Add("ParameterCode",g_cstrSizeParamCode[j].GetString());

		cJsonErrorType[iIndex].Add("ParameterValue",iValue);

		cJsonErrorType[iIndex].Add("Timestamp",cstrTimeStamp.GetString());

		cJsonSend["Parameters"].Add(cJsonErrorType[iIndex]);

		iIndex++;
	}

	
	
		CString cstrYield;

		cJsonCount[0].Add("ParameterCode",g_cstrsSizeCountCode[0].GetString());

		cJsonCount[0].Add("ParameterValue",CountInfo.nBatchTotal);

		cJsonCount[0].Add("Timestamp",cstrTimeStamp.GetString());

		cJsonCount[1].Add("ParameterCode",g_cstrsSizeCountCode[1].GetString());

		cJsonCount[1].Add("ParameterValue",CountInfo.nErrorBatchTotal);

		cJsonCount[1].Add("Timestamp",cstrTimeStamp.GetString());

		cstrYield.Format("%0.2f",CountInfo.nBatchTotal > 0 ? (1 - (double)CountInfo.nErrorBatchTotal / (double)CountInfo.nBatchTotal) * 100 : 100);

		cJsonCount[2].Add("ParameterCode",g_cstrsSizeCountCode[2].GetString());

		cJsonCount[2].Add("ParameterValue",cstrYield.GetString());

		cJsonCount[2].Add("Timestamp",cstrTimeStamp.GetString());

		cJsonSend["Parameters"].Add(cJsonCount[0]);

		cJsonSend["Parameters"].Add(cJsonCount[1]);

		cJsonSend["Parameters"].Add(cJsonCount[2]);
	

	cJsonSend.Add("ProductBarcode",m_strCrrentBatch.GetString());

	cJsonSend.Add("LineCode",m_strLineCode.GetString()); 

	cJsonSend.Add("SectionCode",m_strSectionCode.GetString());

	cJsonSend.Add("EquipmentCode",m_strEquipmentCode.GetString());

	cJsonSend.Add("Timestamp",cstrTimeStamp.GetString());

	std::string strSendMessage,strSendUTF8,strRespon;

	CString cstrMessage;

	int iRet;

	strSendMessage = "[" + cJsonSend.ToString() + "]";

	strSendUTF8 = AsciiToUtf8(strSendMessage);

	iRet = MESReportProcessingParameter((CString)strSendUTF8.c_str(),strRespon);

	if (200 != iRet)
	{
//		cstrMessage.Format(_T("MESReportProcessingParameter;返回码：%d\t返回信息：%s\n发送信息：%s"),iRet,strRespon.c_str(),strSendMessage.c_str());

		//	m_sInit.pLogView->DoSomething("EXCEPTION", (void*)(LPCSTR)cstrMessage,NULL);

//		Log(cstrMessage);

	//	m_record.writeHttpFile(cstrMessage);

		m_cJsonResend.Clear();
		m_cJsonResend = cJsonSend;

		AfxBeginThread((AFX_THREADPROC)ReSendReportProcessingParam,this);
	}
	if (200 == iRet)
	{
		cstrMessage.Format(_T("MESReportProcessingParameter;返回码：%d\t\n发送信息：%s"),iRet,strSendMessage.c_str());

		m_record.writeHttpFile(cstrMessage);
	}
	return 1;
}

int CMes::ReportCountInfo( Total_Count  & CountInfo)
{
	neb::CJsonObject cJsonSend;

	neb::CJsonObject cJsonCount[5];

	//  总数量 DAMQ0011  良品数量 DAMQ0012  外观不良数量 DAMQ0013  尺寸不良数量 DAMQ0014 良品率 DAMQ0015

	

	CString cstrTimeStamp;

	SYSTEMTIME iLocalTime;

	GetLocalTime(&iLocalTime);

	cstrTimeStamp.Format(_T("%04d-%02d-%02dT%02d:%02d:%02d.%03d+08:00"),
		iLocalTime.wYear,iLocalTime.wMonth,iLocalTime.wDay,iLocalTime.wHour,iLocalTime.wMinute,iLocalTime.wSecond,iLocalTime.wMilliseconds);

	cJsonSend.AddEmptySubArray("Parameters");

	CString cstrYield;
	//  总数量 DAMQ0011
	cJsonCount[0].Add("ParameterCode",_T("DAMQ0011"));

	cJsonCount[0].Add("ParameterValue",CountInfo.totalCount);

	cJsonCount[0].Add("Timestamp",cstrTimeStamp.GetString());

	//  良品数量 DAMQ0012
	cJsonCount[1].Add("ParameterCode",_T("DAMQ0012"));

	cJsonCount[1].Add("ParameterValue",CountInfo.totalOKCount);

	cJsonCount[1].Add("Timestamp",cstrTimeStamp.GetString());

	//外观不良数量 DAMQ0013
	cJsonCount[2].Add("ParameterCode",_T("DAMQ0013"));

	cJsonCount[2].Add("ParameterValue",CountInfo.detectNGCount);

	cJsonCount[2].Add("Timestamp",cstrTimeStamp.GetString());

	//尺寸不良数量 DAMQ0014
	cJsonCount[3].Add("ParameterCode",_T("DAMQ0014"));

	cJsonCount[3].Add("ParameterValue",CountInfo.sizeNGCount );

	cJsonCount[3].Add("Timestamp",cstrTimeStamp.GetString());

	//良品率 DAMQ0015
	cstrYield.Format("%0.2f",CountInfo.totalCount > 0 ? ((double)CountInfo.totalOKCount / (double)CountInfo.totalCount) * 100 : 0);

	cJsonCount[4].Add("ParameterCode",_T("DAMQ0015"));

	cJsonCount[4].Add("ParameterValue",cstrYield.GetString());

	cJsonCount[4].Add("Timestamp",cstrTimeStamp.GetString());

	cJsonSend["Parameters"].Add(cJsonCount[0]);

	cJsonSend["Parameters"].Add(cJsonCount[1]);

	cJsonSend["Parameters"].Add(cJsonCount[2]);

	cJsonSend["Parameters"].Add(cJsonCount[3]);

	cJsonSend["Parameters"].Add(cJsonCount[4]);

	cJsonSend.Add("ProductBarcode",m_strCrrentBatch.GetString());

	cJsonSend.Add("LineCode",m_strLineCode.GetString()); 

	cJsonSend.Add("SectionCode",m_strSectionCode.GetString());

	cJsonSend.Add("EquipmentCode",m_strEquipmentCode.GetString());

	cJsonSend.Add("Timestamp",cstrTimeStamp.GetString());

	std::string strSendMessage,strSendUTF8,strRespon;

	CString cstrMessage;

	int iRet;

	strSendMessage = "[" + cJsonSend.ToString() + "]";

	strSendUTF8 = AsciiToUtf8(strSendMessage);

	iRet = MESReportProcessingParameter((CString)strSendUTF8.c_str(),strRespon);

	if (200 != iRet)
	{
		cstrMessage.Format(_T("MESReportProcessingParameter;返回码：%d\t返回信息：%s\n发送信息：%s"),iRet,strRespon.c_str(),strSendMessage.c_str());

		//	m_sInit.pLogView->DoSomething("EXCEPTION", (void*)(LPCSTR)cstrMessage,NULL);

		Log(cstrMessage);

		m_record.writeHttpFile(cstrMessage);
	}

	cstrMessage.Format(_T("MESReportProcessingParameter;返回码：%d\t\n发送信息：%s"),iRet,strSendMessage.c_str());

	m_record.writeHttpFile(cstrMessage);

	return 1;
}

int CMes::ReportOnlieInfo()
{
	int iRet = 0;

	neb::CJsonObject cJsonSend;

	CString cstrTimeStamp,cstrMessage;

	std::string strSendMessage,strSendUTF8,strRespon;

	SYSTEMTIME iLocalTime;

	GetLocalTime(&iLocalTime);

	cstrTimeStamp.Format(_T("%04d-%02d-%02dT%02d:%02d:%02d.%03d+08:00"),
		iLocalTime.wYear,iLocalTime.wMonth,iLocalTime.wDay,iLocalTime.wHour,iLocalTime.wMinute,iLocalTime.wSecond,iLocalTime.wMilliseconds);

	cJsonSend.Add("IsOnline",TRUE);

	cJsonSend.Add("LineCode",m_strLineCode.GetString());

	cJsonSend.Add("SectionCode",m_strSectionCode.GetString());

	cJsonSend.Add("EquipmentCode",m_strEquipmentCode.GetString());

	cJsonSend.Add("Timestamp",cstrTimeStamp.GetString());

	strSendMessage = "[" + cJsonSend.ToString() + "]";

	strSendUTF8 = AsciiToUtf8(strSendMessage);

	iRet = MESReportEquipmentOnlineInfo((CString)strSendUTF8.c_str(),strRespon);

	if (200 != iRet)
	{
		cstrMessage.Format(_T("MESReportEquipmentOnlineInfo：返回码：%d\t返回信息：%s"),iRet,strRespon.c_str());

	//	m_sInit.pLogView->DoSomething("EXCEPTION", (void*)(LPCSTR)cstrMessage,NULL);

		static BOOL bMesInfo = FALSE;

		if (!bMesInfo)
		{
			Log(cstrMessage);

			bMesInfo = !bMesInfo;
		}
		
		m_record.writeHttpFile(cstrMessage);
	}

	cstrMessage.Format(_T("Online：返回码：%d"),iRet);

	m_record.writeHttpFile(cstrMessage);

	return iRet;
}

int CMes::Soap_CheckRecipeVersion(std::string &strResponse)
{
	ParamRecipeVersionExamine paramRecipeVersion;
	neb::CJsonObject cJsonRcv;

	paramRecipeVersion.cstrRecipeCode.Format("%s", m_strRecipeCode);
	paramRecipeVersion.cstrVersion.Format("%s",m_strRecipeVison);
	
	int iRes(-1),nCode(-11);
	

	iRes = Soap_recipeVersionExamine(paramRecipeVersion,cJsonRcv);
	cJsonRcv.Get("code",nCode);
	cJsonRcv.Get("msg",strResponse);

	if (SOAP_OK == iRes && 1 == nCode)
	{
		return 200;
	}
	else
	{
		return nCode;
	}

}



int CMes::CHeckPrecipeVersion(std::string & strResponse)
{
	int iRet = 0;

	neb::CJsonObject cJsonSend;
	neb::CJsonObject cJsonSendList;
	neb::CJsonObject cJsonSendListValue[53];
	neb::CJsonObject cJsonSendValue;
	CString cstrTimeStamp,cstrMessage;

	std::string strSendMessage,strSendUTF8,strRespon;

	SYSTEMTIME m_tNow;


	GetLocalTime(&m_tNow);
	CString  m_cstrNow;
	m_cstrNow.Format("%04d/%02d/%02d %02d:%02d:%02d", m_tNow.wYear, m_tNow.wMonth, m_tNow.wDay, m_tNow.wHour, m_tNow.wMinute, m_tNow.wSecond);
	cJsonSend.Add("EquipPC_ID", std::string(m_cstrSendData.FactoryCode.GetString())); 
	cJsonSend.Add("EquipPC_Password", std::string(m_cstrSendData.TestCode.GetString()));
	cJsonSend.Add("Equip_Code", std::string(m_cstrSendData.EquipmentCode.GetString()));
	cJsonSend.Add("Upload_Time", std::string(m_cstrNow.GetString()));

	CString strData;
	if (m_cstrSendData.nType == 1)
	{
		cJsonSend.Add("Is_Online","true");
	}
	else if (m_cstrSendData.nType == 2)  //设备状态
	{
		strData.Format("%d", m_cstrSendData.EquStatus);
		cJsonSend.Add("Status", std::string(strData.GetString()));
		cJsonSend.Add("START_TIME", std::string(m_cstrNow.GetString()));
		if (m_cstrSendData.StopReason != 999)
		{
			strData.Format("%d", m_cstrSendData.StopReason);
			cJsonSend.Add("REASON_CODE", std::string(strData.GetString()));
		}
		else
		{
			cJsonSend.Add("REASON_CODE","");
		}
	}
	else if (m_cstrSendData.nType == 3) 
	{
		strData.Format("%d", m_cstrSendData.AlarmStatius);
		cJsonSend.Add("ALARM_VALUE", std::string(strData.GetString()));

		strData.Format("A%03d", m_cstrSendData.AlarmCode);
		cJsonSend.Add("ALARM_CODE", std::string(strData.GetString()));

		cJsonSend.Add("START_TIME", std::string(m_cstrNow.GetString()));
	}
	else if (m_cstrSendData.nType == 4)
	{
		cJsonSendListValue[0].Add("Param_Code", "MQSDSD");
		strData.Format("%d", m_cstrSendData.nSetCutSpeed);
		cJsonSendListValue[0].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[1].Add("Param_Code", "MQSDSJ");
		strData.Format("%d", m_cstrSendData.nRealCutSpeed);
		cJsonSendListValue[1].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[2].Add("Param_Code", "FJZLSZ");
		strData.Format("%d", m_cstrSendData.nSetTension);
		cJsonSendListValue[2].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[3].Add("Param_Code", "FJZLSJ");
		strData.Format("%d", m_cstrSendData.nRealTension);
		cJsonSendListValue[3].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[4].Add("Param_Code", "JEMJSM");
		strData.Format("%d", m_cstrSendData.nFoilLife);
		cJsonSendListValue[4].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[5].Add("Param_Code", "JWMJSM");
		strData.Format("%d", m_cstrSendData.nAngleLife);
		cJsonSendListValue[5].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[6].Add("Param_Code", "CQDSM");
		strData.Format("%d", m_cstrSendData.nCutterFrequency);
		cJsonSendListValue[6].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[7].Add("Param_Code", "PYL");
		strData.Format("%d", m_cstrSendData.nPenYouliang);
		cJsonSendListValue[7].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[8].Add("Param_Code", "JPS");
		strData.Format("%d", m_cstrSendData.nProductNum);
		cJsonSendListValue[8].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[9].Add("Param_Code", "CJSJ");
		cJsonSendListValue[9].Add("Param_Value", std::string(m_cstrNow.GetString()));

		cJsonSendListValue[10].Add("Param_Code", "TXZH");
		strData.Format("%d", m_cstrSendData.nPictureFlame);
		cJsonSendListValue[10].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[11].Add("Param_Code", "JCJG");
		if (m_cstrSendData.nResult == 0)
		{
			cJsonSendListValue[11].Add("Param_Value", "NG");
		}
		else
		{
			cJsonSendListValue[11].Add("Param_Value", "OK");
		}
		if (m_cstrSendData.SizeAdd.size() < 9)
		{
			for (int i = 0; i < 9; i++)
			{
				m_cstrSendData.SizeAdd.push_back(0);
			}
		}
		std::vector <CString> code;
		code.push_back("LQG");
		code.push_back("JPG");
		code.push_back("LQK");
		code.push_back("JEG");
		code.push_back("JEK");
		code.push_back("JD");
		code.push_back("JBJ");
		code.push_back("CCDWBQ");
		code.push_back("AT9GD");
		for (int i = 12; i < 21; i++)
		{
			
			cJsonSendListValue[i].Add("Param_Code", std::string(code.at(i-12).GetString()));
			strData.Format("%.3lf", m_cstrSendData.SizeAdd.at(i-12));
			cJsonSendListValue[i].Add("Param_Value", std::string(strData.GetString()));
		}
		code.clear();
		cJsonSendListValue[21].Add("Param_Code", "JH");
		cJsonSendListValue[21].Add("Param_Value", std::string(m_cstrSendData.cstrMaterialNum.GetString()));

		cJsonSendListValue[22].Add("Param_Code", "PF");
		cJsonSendListValue[22].Add("Param_Value", std::string(m_cstrSendData.cstrnpeiFang.GetString()));

		cJsonSendListValue[23].Add("Param_Code", "ZCL");
		strData.Format("%d", m_cstrSendData.nResultAddress);
		cJsonSendListValue[23].Add("Param_Value", std::string(strData.GetString()));

		cJsonSendListValue[24].Add("Param_Code", "FPL");
		strData.Format("%d", m_cstrSendData.nErrorTypeAddress);
		cJsonSendListValue[24].Add("Param_Value", std::string(strData.GetString()));
		code.push_back("WGDWBQ");
		code.push_back("QP");
		code.push_back("LB");
		code.push_back("BD");
		code.push_back("HD");
		code.push_back("HX");
		code.push_back("BX");
		code.push_back("LBA");
		code.push_back("AH");
		code.push_back("TTHLB");
		code.push_back("BJQX");
		code.push_back("BJQXA");
		code.push_back("JJCAX");
		code.push_back("BYXDF");
		code.push_back("JEDL");
		code.push_back("KLQX");
		code.push_back("FGMK");
		code.push_back("TBKDPD");
		code.push_back("TBGDPD");
		code.push_back("JEKDPD");
		code.push_back("JEGDPD");
		code.push_back("TBKDPX");
		code.push_back("TBGDPX");
		code.push_back("JEKDPX");
		code.push_back("JEGDPX");
		code.push_back("A/BCW");
		code.push_back("SLQQX");
		code.push_back("WCP");
		if (m_cstrSendData.nTotalErrorPerBatchAddress.size() < 28)
		{
			for (int i = 0; i < 28; i++)
			{
				m_cstrSendData.nTotalErrorPerBatchAddress.push_back(0);
			}
		}
		for (int i = 25; i < 53; i++)
		{
			
			cJsonSendListValue[i].Add("Param_Code", std::string(code.at(i - 25).GetString()));
			strData.Format("%d", m_cstrSendData.nTotalErrorPerBatchAddress.at(i - 25));
			cJsonSendListValue[i].Add("Param_Value", std::string(strData.GetString()));
		}
		code.clear();
		cJsonSend.AddEmptySubArray("ParamList");
		for (int i = 0; i < 53; i++)
		{
			cJsonSend["ParamList"].Add(cJsonSendListValue[i]);
		}

	}
	else if (m_cstrSendData.nType == 5)
	{

	}


	strSendMessage = cJsonSend.ToString();

	strSendUTF8 = AsciiToUtf8(strSendMessage);

	iRet = MESRequest((CString)strSendUTF8.c_str(),strRespon,CheckEquipmentRecipeVersion);
	CString Message;
	Message.Format("Res: %s  Send: %s", strRespon.c_str(), strSendMessage.c_str());
	strRespon = (CStringA)Message;
	strResponse = strRespon;

	//if (200 != iRet)
	//{
	//	cstrMessage.Format(_T("CHeckPrecipeVersion;返回码：%d\t返回信息：%s\n发送信息：%s"),iRet,strRespon.c_str(),strSendMessage.c_str());

	////	m_sInit.pLogView->DoSomething("EXCEPTION", (void*)(LPCSTR)cstrMessage,NULL);

	//	Log(cstrMessage);

	//	m_record.writeHttpFile(cstrMessage);
	//}

	//cstrMessage.Format(_T("CHeckPrecipeVersion;返回码：%d\t返回信息：%s\n发送信息：%s"),iRet,strRespon.c_str(),strSendMessage.c_str());

	//m_record.writeHttpFile(cstrMessage);

	return iRet;
}

BOOL CMes::WriteUploadTuple(void)
{
	
	try
	{
		CLockHelper cLock(&m_csWriteTuple);

	//	EnterCriticalSection(&m_csWriteTuple);

		WriteTuple(m_hvUploaded,(HTuple)m_cstrUploadTuple);

	//	LeaveCriticalSection(&m_csWriteTuple);
	}
	catch(HException &e)
	{
		CString strException;

		strException.Format("写tuple异常:%s\n",e.ErrorMessage().Text());

		m_record.writeMSG(strException);

	}
	catch(...)
	{
	//	LeaveCriticalSection(&m_csWriteTuple);

		CString strMsg;

		strMsg.Format("写tuple异常\t");

		m_record.writeMSG(strMsg);

		return FALSE;
	}
	return TRUE;
}


BOOL CMes::IsUpload(const CString & cstrFile)  //已经上传 返回FALS，没有上传 返回TRUE
{
	HTuple hvIndex;

	int iRet = -1;

	EnterCriticalSection(&m_csWriteTuple);		//m_csUploadTUple

	TupleFind(m_hvUploaded,HTuple(cstrFile),&hvIndex);

	LeaveCriticalSection(&m_csWriteTuple);

	if (hvIndex.Length() > 0)
	{
		iRet = hvIndex[0].I();
	}
	if (iRet >= 0)		//找到了，表示已经上传
	{
		return FALSE;
	}
	else				//没有找到表示没有上传
	{
		return TRUE;
	}
}


BOOL CMes::AppendUploadTuple(CString & cstrFile)
{
	EnterCriticalSection(&m_csWriteTuple);		//m_csUploadTUple

	m_hvUploaded.Append(HTuple(cstrFile));

	LeaveCriticalSection(&m_csWriteTuple);

	return TRUE;
}


void CMes::Log(const CString &cstrMessage,const CString &cstrType)
{
//	return; //删除弹窗提示

	if (cstrType == "EXCEPTION")
	{
		return;
	}
	try
	{
		switch(/*m_sInit.nProductType*/1)
		{
		case 1 :
			{
				//m_sInit.fLog(cstrType, cstrMessage ,0);
				break;
			}
		case 2:
			{
				break;
			}
		}
	}
	catch (...)
	{

	}
}


void CMes::ReSendReportProcessingParam(void* pVoid)
{
	CMes* pMes = (CMes*)pVoid;
	neb::CJsonObject cJsonSend = pMes->m_cJsonResend;
	std::string strSendMessage,strSendUTF8,strRespon;

	CString cstrMessage;

	int iRet = 0;

	strSendMessage = "[" + cJsonSend.ToString() + "]";

	strSendUTF8 = AsciiToUtf8(strSendMessage);

	int nCount = 0;

	while(nCount < 90)
	{
		iRet = pMes->MESReportProcessingParameter((CString)strSendUTF8.c_str(),strRespon);
		if (200 == iRet)
		{
			break;
		}
		nCount ++;
		Sleep(10000);
	}
	
	cstrMessage.Format(_T("MESReportProcessingParameter;返回码：%d\t\n发送信息：%s"),iRet,strSendMessage.c_str());

	pMes->m_record.writeHttpFile(cstrMessage);

}

void CMes::Soap_ReSendEquipmentProductProcessParam(void* pVoid)
{
	neb::CJsonObject nebCJsonSend;
	neb::CJsonObject nebCJsonReciev;
	CMes* pMes = (CMes*)pVoid;
	ParamEquipmentProductProcess tParam = pMes->m_paramEquipmentProductProcess;
	
	int nCount = 0;
	int nRes(-102),nCode(-103);
	while(nCount < 90)
	{
		nebCJsonSend.Clear();
		nebCJsonReciev.Clear();
		nRes = CMesGSoap::getInstance().EquipmentProductProcessParam(tParam,nebCJsonSend,nebCJsonReciev);
		
		if (SOAP_OK == nRes )
		{
			break;
		}
		nCount ++;
		Sleep(10000);
	}
	{
		CString cstrMsg;
		std::string strTime;
		nebCJsonReciev.Get("code",nCode);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		pMes->m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		pMes->m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		pMes->m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		pMes->m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);
	}
}

int CMes::Soap_getRecipeList(const CString& cstrPruoductCode,neb::CJsonObject & nebCJsonReciev)
{
	neb::CJsonObject nebCJsonSend;
	int res = -101;
	res = CMesGSoap::getInstance().GetRecipeList(cstrPruoductCode,nebCJsonSend,nebCJsonReciev);
	
	{
		CString cstrMsg;
		std::string strTime;
		int nRes(-102),nCode(-103);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		m_pSoapMesLog->GetRecipeListLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		m_pSoapMesLog->GetRecipeListLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		m_pSoapMesLog->GetRecipeListLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		m_pSoapMesLog->GetRecipeListLog(cstrMsg);
	}
	
	return res;
}
int CMes::Soap_getRecipe(const CString& cstrRecipeCode,neb::CJsonObject & nebCJsonReciev)
{
	neb::CJsonObject nebCJsonSend;
	int res = -101;
	res = CMesGSoap::getInstance().GetRecipe(cstrRecipeCode,nebCJsonSend,nebCJsonReciev);

	{
		CString cstrMsg;
		std::string strTime;
		int nRes(-102),nCode(-103);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		m_pSoapMesLog->GetRecipeLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		m_pSoapMesLog->GetRecipeLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		m_pSoapMesLog->GetRecipeLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		m_pSoapMesLog->GetRecipeLog(cstrMsg);
	}

	return res;
}
int CMes::Soap_recipeVersionExamine(const ParamRecipeVersionExamine& paramRecipeVersion,neb::CJsonObject & nebCJsonReciev)
{
	neb::CJsonObject nebCJsonSend;
	int res = -101;
	res = CMesGSoap::getInstance().RecipeVersionExamine(paramRecipeVersion,nebCJsonSend,nebCJsonReciev);
	{
		CString cstrMsg;
		std::string strTime;
		int nRes(-102),nCode(-103);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		m_pSoapMesLog->RecipeVersionExamineLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		m_pSoapMesLog->RecipeVersionExamineLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		m_pSoapMesLog->RecipeVersionExamineLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		m_pSoapMesLog->RecipeVersionExamineLog(cstrMsg);
	}
	
	return res;
}

int CMes::Soap_recipe(const ParamRecipe& pRecipe,neb::CJsonObject & nebCJsonReciev)
{
	neb::CJsonObject nebCJsonSend;
	int res = -101;
	res = CMesGSoap::getInstance().Recipe(pRecipe,nebCJsonSend,nebCJsonReciev);
	
	{
		CString cstrMsg;
		std::string strTime;
		int nRes(-102),nCode(-103);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		m_pSoapMesLog->RecipeLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		m_pSoapMesLog->RecipeLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		m_pSoapMesLog->RecipeLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		m_pSoapMesLog->RecipeLog(cstrMsg);
	}
	return res;
}
int CMes::Soap_equipmentProductProcessParam(const ParamEquipmentProductProcess & pProductProcess,neb::CJsonObject& nebCJsonSend,neb::CJsonObject & nebCJsonReciev)
{
	
	m_paramEquipmentProductProcess = pProductProcess;
	int res(-101),nCode(-11);
	res = CMesGSoap::getInstance().EquipmentProductProcessParam(pProductProcess,nebCJsonSend,nebCJsonReciev);
	nebCJsonReciev.Get("code",nCode);
	if (SOAP_OK == res )
	{
		CString cstrMsg;
		std::string strTime;
		int nRes(-102),nCode(-103);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		m_pSoapMesLog->EquipmentProductProcessLog(cstrMsg);
	}
	else
	{
		AfxBeginThread((AFX_THREADPROC)Soap_ReSendEquipmentProductProcessParam,this);
		Sleep(200);
	}
	
	return res;
}
int CMes::Soap_CCDFileUploadComplete(const std::vector<ParamCCDUploadFile> & vecParamCCDUpload,neb::CJsonObject & nebCJsonReciev)
{
	neb::CJsonObject nebCJsonSend;
	int res = -101;
	res = CMesGSoap::getInstance().CCDFileUploadComplete(vecParamCCDUpload,nebCJsonSend,nebCJsonReciev);
	
	{
		CString cstrMsg;
		std::string strTime;
		int nRes(-102),nCode(-103);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		m_pSoapMesLog->CCDFileUploadCompleteLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		m_pSoapMesLog->CCDFileUploadCompleteLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		m_pSoapMesLog->CCDFileUploadCompleteLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		m_pSoapMesLog->CCDFileUploadCompleteLog(cstrMsg);
	}
	return res;
}

int CMes::GetParamCCDUploadFiles(const CString& cstrURI,std::vector<ParamCCDUploadFile>& vecParam)
{
	vecParam.clear();
	ParamCCDUploadFile par;
	par.cstrSFC.Format("%s",m_strCrrentBatch);
	par.cstrURI.Format("%s",cstrURI);
	if (cstrURI.Find(_T("_OK_")) > 0 ||cstrURI.Find(_T(".csv")) > 0 )		//OK 图片 或csv 文件  
	{
		par.nPassed = 0;
	}
	else
	{
		par.nPassed = 1;
	}
	vecParam.push_back(par);
	return 0;
}
int CMes::Soap_Heatbeat(const bool & isOnline,neb::CJsonObject & nebCJsonReciev)
{
	neb::CJsonObject nebCJsonSend;
	int res = -101;
	res = CMesGSoap::getInstance().Heartbeat(isOnline,nebCJsonSend,nebCJsonReciev);
	{
		CString cstrMsg;
		std::string strTime;
		int nRes(-102),nCode(-103);
		nebCJsonSend.Get("SendTime",strTime);
		cstrMsg.Format("开始调用：,%s",strTime.c_str());
		m_pSoapMesLog->HeatBeatLog(cstrMsg);

		cstrMsg.Format("发送：,%s",nebCJsonSend.ToString().c_str());
		m_pSoapMesLog->HeatBeatLog(cstrMsg);

		nebCJsonReciev.Get("RcvTime",strTime);
		nebCJsonReciev.Get("Res",nRes);
		nebCJsonReciev.Get("code",nCode);
		cstrMsg.Format("结束调用：,%s, 调用：%s , 返回码 ：%d",strTime.c_str(),SOAP_OK == nRes ? "成功":"失败",nCode);
		m_pSoapMesLog->HeatBeatLog(cstrMsg);

		cstrMsg.Format("接收：,%s",nebCJsonReciev.ToString().c_str());
		m_pSoapMesLog->HeatBeatLog(cstrMsg);
	}
	return res;
}
